Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Tuesday, July 4, 2017

Use of Mutability in Java


An immutable class is a class whose state cannot be changed. This can be done in three ways.

  • Private: If a field is private, it cannot be externally changed. If it's a final, you cannot accidentally change it. 
  • Do not provide the setter: In support to the earlier point, if the fields are private and no setter is provided, this class fields always remain the same. 
  • Declare as final: Sub-classes should not be able to override the methods. 


Pro's:


  • Immutable objects can make life easier. An immutable object is automatically thread-safe, and it has no synchronization issues. They make concurrent programming safer and cleaner.
  • Immutable objects do not need a copy constructor or an implementation of clone. For the sake of simplicity.
  • When an immutable object throws any exception, it will never result with the object left in an indeterminate state. - atomicity by Joshua Bloch in Effective Java


Con's:

  • Making copies of objects in order to mutate them can drain our resources, especially when dealing with complex data structures. Also, changing objects with a distinct identity can be also more intuitive.

In Effective Java, Joshua Block writes:
“Classes should be immutable unless there’s a very good reason to make them mutable. If a class cannot be made immutable, limit its mutability as much as possible.”


Immutability can solve many problems and make your life easier, especially when it comes to working in a concurrent environment.