Thursday, July 14, 2011

Immutation in JAVA Explained

Watched X-Men, mutants were far more stronger than a normal  human being. I recalled my biology class where we studied genetics and chromosomal mutations. Mutations were triggered to make species better. I left biology and am now into software. Here also we do the same thing "Mutate". We override objects of the existing classes in the SDK/API/Framework to make them better or fit to our need. But you cannot override each and every object of the SDK/API,  they are protected from getting or being mutated for a reason. Making decisions on creating immutable class needs thorough analysis. How do I create a class which cannot be mutated?

In JAVA String class is a good example, its immutable.

Below are the rules that must be followed in order to create an immutable object.

1. No "setter" methods — methods that modify class members or objects referred to by class variables.
2. Make all class variables final and private.
3. Do not allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
4. If the instance fields include references to mutable objects, don't allow those objects to be changed:
       * Do not provide methods that modify the mutable objects.
       * Do not share references to the mutable objects.
5. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies.
6. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.


Immutable laws of the universe can teach more exalted lessons than the holy books.
-S

No comments: