I recently started working in Java and was introduced to the wild and crazy world of getters and setters for everything. I hated it at first, but quickly got used to it. Too used to it.
I have been spending a lot of time lately thinking more about class design. One of the things I am trying to do is avoid the trap of doing getters and setters for everything. However, much of the work I do is with entities that are mainly data containers and I am not certain that getters and setters are actually inappropriate in these cases.
Here is a simple example using public properties.
class Space {
public String name;
public String description;
Space(final String name, final String description) {
this.name = name;
this.description = description;
}
}
Here is a simple example using private properties and using getters and setters.
class Space {
private String name;
private String description;
Space(final String name, final String description) {
this.name = name;
this.description = description;
}
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
public String getDescription() {
return this.description;
}
public void setDescription(final String description) {
this.description = description;
}
}
In these examples, both the name
and the description
fields should be able to be changed.
I feel like the getter/setter example is more clear and hides the implementation details of what name
and description
are. It would also allow for validation on set later if needed.
I have read several discussions about getters and setters being evil and/or an anti-pattern, but it really feels like those might not apply to this situation.
Maybe there are some options I have not yet considered. I'm open for suggestions!