Search code examples
javaanti-patterns

Is it in an anti-pattern to always use get and set methods to access a class's own member fields?


In Java classes is it considered good or bad practice to access member fields with their getters and setters?

e.g which is better:

public Order {
    private Agreement agreement;

    public Agreement getAgreement() {
    return agreement;
    } 

    public void process() {
       //should I use:
       getAgreement().doSomething();
       //Or:
       agreement.doSomething();
    }
}

In general I think accessing the field directly is best due to the KISS principle and also someone may override the get method later with unpredictable results.

However my colleagues argue that it is better to keep a layer of abstraction. Is there any consensus on this?


Solution

  • The core issue here is that direct field access is ineligible for interception by subclass overridden methods, AOP, dynamic proxies and the like. This can be a good or bad thing depending on the case. I would say that using getters and setters internally is not an anti-pattern or a pattern. It is a good or bad thing depending on the situation, and the design of your class.