Benefits of making a class immutable
Lets first identify benefits of making a class immutable. Immutable classes are- are simple to construct, test, and use
- are automatically thread-safe and have no synchronization issues
- do not need a copy constructor
- do not need an implementation of clone
- allow hashCode to use lazy initialization, and to cache its return value
- do not need to be copied defensively when used as a field
- make good Map keys and Set elements (these objects must not change state while in the collection)
- have their class invariant established once upon construction, and it never needs to be checked again
- always have “failure atomicity” (a term used by Joshua Bloch) : if an immutable object throws an exception, it’s never left in an undesirable or indeterminate state
- Make all fields final and private
- Don’t provide “set” method
- Don’t allow subclasses to override methods, declare class final
- If need return immutable instance variable, always return a copy of it
- Using Collections.unmodifiableList() to get a read-only list, same for set and map. This is to avoid somebody using reflection to get private field directly.
- stop reflection to access private field, using a SecurityManager and a sufficiently restrictive security policy. //TODO
http://javarevisited.blogspot.ca/2013/03/how-to-create-immutable-class-object-java-example-tutorial.html
Another way to make class immutable is to use cglib
cglib’s ImmutableBean allows you to create an immutability wrapper similar to for example Collections#immutableSet. All changes of the underlying bean will be prevented by an IllegalStateException
http://www.javacodegeeks.com/2013/12/cglib-the-missing-manual.html
No comments:
Post a Comment