Immutable means that the object CANNOT change. Thus, the standard String object in Java is immutable - you can pass it, you can store as many links as you want, but you cannot change it. If you want to change a string, you must use StringBuilder (or StringBuffer) to add or change.
But String is a class that is part of the embedded system, so its immutability can be taken at face value. If you want to create an immutable class, then you can do this only by providing methods that are guaranteed not to change its internal state. Since a class is usually valid, it is possible that part of the code may subclass your class just to change its internal state.
Thus:
- Make all your fields internal. They should also be marked as final, as they should only be installed from the designer.
- DO NOT return fields that are themselves objects unless they are also immutable.
- Mark final object and all final methods
- DO NOT provide any methods that may change the internal state
- Operations such as clone (), add (), subtract (), split (), diff (), comb (), etc. that spit out new objects should not refer to an existing object or its fields on the safe side Use a deep copy to ensure thread safety.
- If your object returns collections of other objects, use methods such as Collections.unmodifiableList (), unmodifiableMap (), etc. to stop people abusing these collections.
- Similarly, if an object or any field implements interfaces intended for read / write operations, then throw exceptions when implementing any write operation.
Irreplaceability is a good quality for objects (especially those where ownership can be a problem, or concurrency), but the disadvantage is that you can build many discarded objects, and therefore they can be inefficient. So this is a compromise, and it depends on what you need for the objects, whether it's worth it.
locka
source share