简体   繁体   中英

Java fields and accessor methods, from within the class

Is using Java fields directly or using the accessor method better? 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. 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.

There is actually a case where using the accessor method is better, but only in classes designed for extension. This is for example very common in the code of the 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.

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