简体   繁体   English

类中的Java字段和访问器方法

[英]Java fields and accessor methods, from within the class

Is using Java fields directly or using the accessor method better? 是直接使用Java字段还是使用accessor方法更好? Within the same class. 在同一个班内。

Example: 例:

private ArrayList<String> list;

list.get(0);

or 要么

getList().get(0);

Within the same class it fine to access the members directly, the encapsulation and hiding is intended for out of the class. 在同一个类中,可以直接访问成员,封装和隐藏是出于类之外的目的。

When you think about it, you access it directly anyway: 当您考虑它时,可以直接访问它:

private void useList()
{
    String temp = getList().get(0); // access "via accessor" ----------+
    System.out.println(temp);                                          |
}                                                                      |
                                                                       |
public ArrayList<String> getList()                                     |
{                                                                      |
    return theList; // but you actually directly access it here...  <--+
}

Accessing members through methods (also when accessing them from inside the same class) makes your code better maintainable. 通过方法访问成员(也可以从同一类内部访问成员)使您的代码更易于维护。 Consider in a future version of your class the list is no longer stored in that class, but in some other location. 考虑在该类的将来版本中,列表不再存储在该类中,而是存储在其他位置。 Or maybe the values in the list become derived and you want the list to be derived on the spot. 或者,列表中的值可能已派生,而您希望当场派生该列表。 In such situations the 'getter/setter' method could save work, bugs and duplicated code. 在这种情况下,“ getter / setter”方法可以节省工作,错误和重复的代码。 You just code your new logic in the getter and you are good to go! 您只需在吸气剂中编写新逻辑即可,一切顺利! So, if maintainability is desired, use getters and setters. 因此,如果需要可维护性,请使用吸气剂和吸气剂。

You should do what you believe is simpler or clearer. 您应该做自己认为更简单或更清楚的事情。

The performance difference is next nothing once the code has warmed up. 代码预热后,性能上的区别几乎是零。 It tests I have done on simpler cases the difference can be less than 0.1 ns on average. 我在较简单的情况下进行的测试表明,平均差异可以小于0.1 ns。

There is actually a case where using the accessor method is better, but only in classes designed for extension. 实际上,在某些情况下,使用accessor方法更好,但仅在为扩展设计的类中使用。 This is for example very common in the code of the Spring Framework. 例如,这在Spring Framework的代码中非常常见。 You can write a protected accessor method that a client of your API can then override and provide something completely different instead of your private field. 您可以编写一个protected访问器方法,然后您的API客户端可以覆盖该方法,并提供与您的私有字段完全不同的内容。

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

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