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
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.
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.
Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With