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

This is only from an academic point of view. All I know is that whenever we want to make some class immutable - it should consist of final primitive fields - the link does not slip away when building the object - if it uses other objects, then these objects should also be recursively immutable or API immutable classes, such as java.lang.String, among some other detailed observations!

But I recently came up with a question in which the interviewer asked the candidate to create an immutable class that has java.util.Date in it. My first impression is that it is not possible, although we can do workarounds with a string containing a date string, and not directly in a Date object.

Please clarify this. Thanks.

+5
source share
3 answers

The simplest task to make this class immutable is to create a protective copy of the Date object (when it is passed in the build parameters). Then do not provide any setters. Thus, the reference to the Date field in the class is not visible to code outside this class, and therefore Date cannot be changed.

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

(Getter should also return a copy of the date field, since the date itself has been changed, and changing the returned field from the recipient will also change the class field.)

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

+15
source

I suggest creating a wrapper class around the date used and not providing any setters or any method that can actually change the value.

To make it immutable, you need to consider the following things:

  • You need to make sure that the class cannot be overridden - make it final.
  • Make all fields private and final.
  • Do not provide any setters or any method that modifies an instance variable.
  • Protective copying of objects between the called and the calling.

    Consider this tutorial for more

+5
source

1) Do not provide "setter" methods.

2) Make all fields final and private

3) Do not let subclasses override methods. Declare class as final

4) For mutable instance variables - Ex date: In this case, special attention should be paid.

5) Make the constructor private and create instances in the factory methods. Factory method of storing the logic of creating an object in one place.

public static MyImmutableClass createNewInstance(Integer fld1, String fld2, Date date) { return new MyImmutableClass (fld1, fld2, date); } 

6) Instead, a new Date object should be returned with the content copied to it.

 public Date getDateField() { return new Date(dateField.getTime()); } 

- Here, dateField is a field that is set inside a private constructor

0
source

Source: https://habr.com/ru/post/1212944/


All Articles