Rule 3: Ensure Immutability
Class is said to be immutable if the instance of a class(Object ) can not be modified once created. Java provided immutable classes are String, BigInteger, BigDecimal etc.
It ensures thread safety and other maintainability aspects.
Following are the five steps to ensure immutability of a class:
- Make sure the fields of a public class are private so it’s not accessible from outside.
- Make the fields final so that it doesn’t hold new value
- Ensure that a class should not be sub-classed as it leads to appearance as if it is modified.it can be done by making class final.
- Don’t give any mutators.
- Ensure exclusive access to any mutable components: If your class has any fields that refer to mutable objects, ensure that clients of the class cannot obtain references to these objects. Never initialize such a field to a client-provided object reference or return the field from an accessor. Make defensive copies
The UNDERLINING thing:
The source-code with Mutable object or field-data and is in unshared state is thread-safe.
The code with immutable object and shared state is also thread safe. Problem arises when the code is shared and mutable.
Why to use?Advantages–
- Immutable objects are INHERENTLY thread-safe so the immutable object should ENCOURAGE the CLIENT CODE to use the EXISTING INSTANCES instead of creating new ones.This can be done by using public static final constants and there is a more way ,by creating static factory methods: ITEM1.
- This has low MEMORY FOOTPRINT and decreases the GARBAGE COLLECTION COST.
- Immutable objects are best member choice for maps and sets.
disadvantages–
- The major disadvantage of immutable classes is that they require a separate object for each distinct value.
Conclusion
As a thumb rule make fields private final,unless there is a good reason to-do-otherwise.
As a thumb rule,don’t provide the separate initilizers(or mutator) other than constructors, unless there is a good reason to do otherwise.