Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Clone the property inside getter method

Folks,

I was going through Java's best coding practises mentioned here
http://viralpatel.net/blogs/most-useful-java-best-practice-quotes-java-developers/

2nd quote says,

Quote 2: Never make an instance fields of class public

I agree that's absolutely correct, but I got stuck for following writer's recommendation few lines below this quote.

He says,


private String[] weekdays = 
    {"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};

public String[] getWeekdays() {
    return weekdays;
}

But writing getter method does not exactly solve our problem. The array is still accessible. Best way to make it unmodifiable is to return a clone of array instead of array itself. Thus the getter method will be changed to

public String[] getWeekdays() {
    return weekdays.clone();
}

I have never myself used clone() inside any getter method of Java class.

I am wondering ( as it is mentioned to be one of the good practises ) - why one should use / shouldn't use clone() inside getter method ? and in which scenarios ?

Does it qualify to be a good coding practise for Java ?

Thanks

like image 746
Saurabh Gokhale Avatar asked Sep 24 '12 06:09

Saurabh Gokhale


People also ask

Should a getter return a copy?

So the rule of thumb is: Do not return a reference of the original object in the getter method. Instead, it should return a copy of the original object.

How clone method works internally in Java?

java cloning is field by field copy i.e. as the Object class does not have idea about the structure of class on which clone() method will be invoked. 1) If the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned.

Does a getter have a return type?

Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc.


1 Answers

This is discussed in the book "Effective Java" by Joshua Bloch. There's a section called "Make defensive copies when needed" (Section 39 in 2nd edition).

https://www.informit.com/articles/article.aspx?p=31551&seqNum=2

A good book to dwell on topics like this.

like image 159
madth3 Avatar answered Oct 15 '22 23:10

madth3