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?