A getter doesn't have to read a field. It can calculate the value from other fields. That's a derived getter.
public class Person { private String firstName; private String lastName; public String getFirstName() { return firstName; // just reads } public String getLastName() { return lastName; // just reads } }
public class Person { private String firstName; private String lastName; public String getFullName() { // no fullName field exists return firstName + " " + lastName; } }
fullName field. The getter computes the result from the existing fields each time it's called. Storing it would be redundant.
firstName, lastName, and a fullName field means three places to keep in sync — if someone changes their last name and you forget to update fullName, you have a bug. Derived getters can never go stale.
public class Hotel { private int numberOfSuites; private int numberOfRooms; private int bookedSuites; private int bookedBasicRooms; private int availableSuites; // extra! private int availableRooms; // extra! public int getAvailableSuites() { return availableSuites; // hope it's accurate... } }
bookedSuites and availableSuites — forget once and the data is wrong.
public class Hotel { private int numberOfSuites; private int numberOfRooms; private int bookedSuites; private int bookedBasicRooms; public int getAvailableSuites() { return numberOfSuites - bookedSuites; } public int getAvailableRooms() { return numberOfRooms - bookedBasicRooms; } }
getAvailableSuites() and getAvailableRooms() should be derived getters with no backing variable.