简体   繁体   English

Java - 克隆 getter 方法中的属性

[英]Java - Clone the property inside getter method

Folks,各位,

I was going through Java's best coding practises mentioned here我正在浏览此处提到的 Java 最佳编码实践
http://viralpatel.net/blogs/most-useful-java-best-practice-quotes-java-developers/ 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引用 2:永远不要公开类的实例字段

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.但是编写 getter 方法并不能完全解决我们的问题。 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因此 getter 方法将更改为

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

I have never myself used clone() inside any getter method of Java class.我自己从未在 Java 类的任何 getter 方法中使用过clone()

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 ?我想知道(因为它被提到是一种良好的做法) - 为什么should use在 getter 方法中should use / shouldn't use clone() and in which scenarios ?在哪些情况下?

Does it qualify to be a good coding practise for Java ?它是否有资格成为 Java 的良好编码实践?

Thanks谢谢

This is discussed in the book "Effective Java" by Joshua Bloch .这在Joshua Bloch 的“Effective Java”一书中讨论过。 There's a section called "Make defensive copies when needed" (Section 39 in 2nd edition).有一个部分称为“需要时制作防御性副本” (第 2 版第 39 节)。

https://www.informit.com/articles/article.aspx?p=31551&seqNum=2 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:如果不使用clone方法,这个类的用户可以做很多不道德的事情:

  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.如果你想保证整个对象图(包含数组)是不可变的,你可以在get() clone() or System.arraycopy()clone() or System.arraycopy() 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.这通常在公开数组的 API 是公共的并且数组中的值存在约束或对象被多个线程访问时完成。 In such cases the immutability is important.在这种情况下,不变性很重要。

Let say, you have a GroceryStore object that has getItemsSortedByPrice() method.假设您有一个具有getItemsSortedByPrice()方法的GroceryStore对象。 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.如果这是内部代码(即)不是公共 API 的一部分,并且您知道您不会修改数组,那么克隆/应对可能没有必要,因为它会损害性能而没有真正的好处。

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.数组只是对象,适用于普通对象的所有 (im) 可变性规则/实践也适用于数组。

I think your usecase is not matching the proposed Java code.我认为您的用例与建议的 Java 代码不匹配。 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.最后一个数组对我来说听起来像Enums ,我认为这更符合您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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