Effective Java Item 15: Minimise mutability
What is immutability?
Immutability is an object that does not change its state after it has been instantiated.
How to make an object immutable in java?
- Don’t provide setters(mutators)
- Make sure the class cannot be extended by making the final, or has a private constructor(one class cannot extend another class that has no default constructor, when you have a private constructor, you can have a static public function to build that object)
- Make all fields final (This rule can be broke sometimes. For example, because the hash value of a immutable object will never change, you may want to cache the hash value after the first time the hashCode() function is invoked)
- Make all fields private
- Ensure exclusive access to any mutable components (I don’t get what does this means)
What are the advantages of immutable object?
Immutable objects are thread safe, because the state of that object will never be changed, so when different process/thread try to read that object will always get the same result. So it makes concurrent programming a lot cleaner and easier to write.
What are the disadvantages of immutable object?
Every time you want to modify an object you have to create a new one. This may cause out of memory issue when creating a lot of big/complicated objects.