Why is Immutability Important in Java Class Design?
Join the DZone community and get the full member experience.
Join For Freelet’s revisit another common topic which java programmers deal with on a daily basis – immutable objects and classes . one of the most prominent examples being the java.lang.string class
how is this related to java?
an ‘immutable’ object is one whose instance cannot be changed once created.
how to ensure ‘immutability’?
well, general oo rules apply here as well (think encapsulation)
- all fields (member variables) should be made private and final
- do not provide any ‘ setter ‘ methods (mutators)
- don’t allow your class to be extended – you can either declare the class final or make the constructor private . in case you choose to use a private constructor, use a static factory method to create instances for the clients (in a defensive manner of course!)
- make defensive copies of any ‘mutable’ members which you might have as a part of your class i.e. do not provide direct access to the references of the mutable members. otherwise, the client api may unknowingly change the state of the mutable object which you returned which in turn will create loads of other issues
click to see the code snippet below
lets look at the client class which creates ‘mutable’ instance of the person class
when we execute this class, the results are as follows (not so good)
abhishek was born on mon feb 17 19:19:00 est 2014
confirming abhishek’s dob:::: wed dec 31 19:00:00 est 1969
let’s look at an improved version – immutable version of the person class
you should consider immutability of your classes if you need
- thread safety : immutable objects do not need synchronization and are unharmed even during concurrent access by multiple threads.
- simplicity : dealing with classes which would encapsulate your immutable object (via composition)
to sum it up
it’s not as if you have to make every class immutable! but do remember that one should aim for immutability until and unless there is a very strong reason for not doing so e.g. you are writing an api and you know that your mutable object is accessible within the confines of your control and not really a part of the public interface of the api. this way, you are sure that the ‘client’ class is within your control and will not undue advantage of the mutable nature of the object
that’s it……… !
happy reading folks :-)
Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2
-
DevOps Midwest: A Community Event Full of DevSecOps Best Practices
-
Front-End: Cache Strategies You Should Know
-
What Is JHipster?
Comments