Chapter 73. Simple Value Objects
Steve Freeman
Classes that represent Value Objects don’t need getters or setters. Java developers are usually taught to use getters for accessing fields, like this:
public class Coordinate {
private Latitude latitude;
private Longitude longitude;
public Coordinate(Latitude latitude, Longitude longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
/**
* @return the latitude of the Coordinate
*/
public Latitude getLatitude() {
return latitude;
}
/**
* @return the longitude of the Coordinate
*/
public Longitude getLongitude() {
return longitude;
}
}
System.out.println(thing.getLatitude());
The idea is that getters encapsulate how values are represented in an object, providing a consistent approach across a codebase. It also allows for protection against aliasing, for example, by cloning collections before returning them.
The style has its origins in the early days of JavaBeans, when there was a lot of interest in graphical tooling using reflection. There might also have been some influence from Smalltalk (the classic object-oriented language), in which all fields are private unless exposed via an accessor; read-only fields have getters, but no setters.
In practice, not all classes play the same role and, lacking an alternative structure in the language, many coders write Java classes that are actually Value Objects: a simple set of ...