Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a class immutable with Date object in it?

This is just from an academic learning point of view. All I know is that whenever we want to make some class immutable, - it has to consist of final primitive fields - reference does not escapes during construction of object - if uses other objects, then those objects need to be recursively immutable too or API immutable classes like java.lang.String, among some other detailed lookouts!

But I recently came accross a question wherein an interviewer asked a candidate to create an immutable class that has a java.util.Date in it. My first impression tells that its not possible although we can do workarounds with String containing the date string rather than in Date object itself.

Please clarify me on this. Thank you.

like image 245
xploreraj Avatar asked Feb 09 '15 08:02

xploreraj


2 Answers

The simplest thing to do here to make the class immutable is to create a defensive copy of the Date object (when it is passed in the construction parameters). Then don't provide any setters as well. Like this no reference to the Date field in the class is visible to code outside this class and thus the Date can't be modified.

See Tom's comment for required getter characteristic! Thanks for the addition.

(Getter should return a copy of the date field as well, since Date itself is mutable, and changing the returned field from the getter will change the class's field as well.)

For more information and details: http://www.informit.com/articles/article.aspx?p=31551&seqNum=2

like image 87
DrunkenPope Avatar answered Oct 12 '22 18:10

DrunkenPope


I suggest to create a wrapper class around the date which you are using and dont provide any setters or any method which can actually change the value.

For making it immutable you need to consider following things :

  1. You need to make sure that the class cannot be overridden, - make it as final.

  2. Make all the fields as private and final.

  3. Dont provide any setters or any method which changes the instance variable.

  4. Defensively copying the objects between callee and caller.

    Consider this tutorial for more

like image 36
shikjohari Avatar answered Oct 12 '22 16:10

shikjohari