Providing unmutability to receivers

From MediaWiki

Jump to: navigation, search

In this article we present how unmutability can be achieved in Java applications using certain techniques which will be available in JDK7. Richard Gomes


In order to understand what this is all about, I recommend you first read an article I've written on strong type checking, where I talk about JSR-308 and how it can be used in order to add semantic meaning to Java types.


We could use JSR-308 in order to avoid the possibility that a receiver changes a copy of an object. The code below compiles:

public class ReceiverTest {

	static class Constants {
	    static final public double PI = 3.1415926536;
	}

	ReceiverTest() {
		double x = Constants.PI;
		x = 2.0;
		
		if (x != Constants.PI) throw 
                  new UnsupportedOperationException("Receiver was modified");
	}
}

... but we could avoid the modification of "x" by declaring:

    static final public double PI = 3.1415926536 @ReadOnly;

... which could provoke a compiler error triggered by an annotation processor.

The beauty of this solution is that everything happens at compilation time.


Richard Gomes 23:18, 27 March 2008 (UTC)