Enforced immutability: Difference between revisions

+Java
m (added haskell)
(+Java)
Line 66:
msg = "Hello World"
</lang>
=={{header|Java}}==
Primitive types in Java can be made immutable by using the <code>final</code> modifier (works on any primitive type):
<lang java>final int immutableInt = 4;
int mutableInt = 4;
mutableInt = 6; //this is fine
immutableInt = 6; //this is an error</lang>
Using final on an object type does not necessarily mean that it can't be changed. It means that the "pointer" cannot be reassigned:
<lang java>final String immutableString = "test";
immutableString = new String("anotherTest"); //this is an error
final StringBuffer immutableBuffer = new StringBuffer();
immutableBuffer.append("a"); //this is fine and it changes the state of the object
immutableBuffer = new StringBuffer("a"); //this is an error</lang>
Objects can be made immutable (in a sense that is more appropriate for this task) by using <code>final</code> and <code>private</code> together to restrict access to instance variables and to ensure that only one assignment is done:
<lang java>public class Immute{
private final int num;
private final String word;
private final StringBuffer buff; //still mutable inside this class, but there is no access outside this class
 
public Immute(int num){
this.num = num;
word = num + "";
buff = new StringBuffer("test" + word);
}
 
public int getNum(){
return num;
}
 
public String getWord(){
return word; //String objects are immutable so passing the object back directly won't harm anything
}
 
public StringBuffer getBuff(){
return new StringBuffer(buff);
//using "return buff" here compromises immutability, but copying the object via the constructor makes it ok
}
//no "set" methods are given
}</lang>
In the <code>Immute</code> class above, the "buff" variable is still technically mutable, since its internal values can still be changed. The <code>private</code> modifier ensures that no other classes can access that variable. The <code>final</code> modifier ensures that it can't be reassigned. Some trickery needed to be done to ensure that no pointers to the actual mutable objects are passed out. Programmers should be aware of which objects that they use are mutable (usually noted in javadocs).
=={{header|JavaScript}}==
 
Anonymous user