Search code examples
javacoding-styleclonegetter-setter

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


Solution

  • 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.