简体   繁体   中英

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

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.

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

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

If you don't use clone method, the user of this class can do a lot of unethical things:

  1. change the order of days,
  2. change the name of days,
  3. ...

But, returning a clone won't affect the class and it's data. So, other users of class won't be affected.

You clone() or System.arraycopy() on get() if you want guarantee that the whole object graph (that contains the array) is immutable. This is done usually when the API that exposes the array is public and there are constraints on the values in the array or when the objects are accessed by multiple threads. In such cases the immutability is important.

Let say, you have a GroceryStore object that has getItemsSortedByPrice() method. You keep the items in array that maintains the order by price, but if you return this array, the client code can possibly modify it and break the (internal) invariants of your object.

If this is internal code (ie) not part of the public API, and you know that you wont modify the array, then cloning/coping probably is not necessary as it hurts performance without real benefit.

All depends on the context.

Arrays are just objects, and all (im)mutability rules/practices that apply to an ordinary object, apply to arrays too.

I think your usecase is not matching the proposed Java code. The example is for a different usecase than yours.

A final array sounds to me like Enums and i think this is matching your requirement much better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM