Java OOP – Should Class Methods Call Its Own Getters and Setters?

javaobject-orientedprogramming practices

Where I work I see lots of classes that do things like this:

public class ClassThatCallsItsOwnGettersAndSetters {

    private String field;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public void methodWithLogic() {
        setField("value");
        //do stuff
        String localField = getField();
        //do stuff with "localField"
    }
}

If I wrote this from scratch, I would have written the methodWithLogic() like this instead:

public class ClassThatUsesItsOwnFields {

    private String field;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public void methodWithLogic() {
        field = "value";
        //do stuff            
        //do stuff with "field"
    }
}

I feel that when the class calls its own getters and setters, it makes the code harder to read. To me it almost implies that complex logic is happening in that method call even though in our case it almost never is. When I'm debugging some unfamiliar code, who's to say that the bug isn't some side effect in that method? In other words, it makes me take lots of side trips on the journey of understanding the code.

Are there benefits to the first method? Is the first method actually better?

Best Answer

I won't say which is better or worse, because that partly depends on your situation (in my opinion). But consider that your getters and setters may change implementation later, and bypassing them would skip that logic.

For example, what happens if you add a "dirty" flag to some setter fields later? By calling your setters in your internal code you'll set the dirty flag without changing any other code. In many situations this would be a good thing.