← Back to Week 5

Derived Getters

A getter doesn't have to read a field. It can calculate the value from other fields. That's a derived getter.

Stored Getter reads a field
public class Person {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName; // just reads
    }
    public String getLastName() {
        return lastName; // just reads
    }
}
How it works: Each getter returns the value of a backing field. Most getters are like this — they're a controlled door to the data inside.
Derived Getter calculates
public class Person {
    private String firstName;
    private String lastName;

    public String getFullName() {
        // no fullName field exists
        return firstName + " " + lastName;
    }
}
How it works: No fullName field. The getter computes the result from the existing fields each time it's called. Storing it would be redundant.
Why bother? Anything calculable from existing data should be derived, not stored. Storing both 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.
firstName Stored
lastName Stored
middleName Stored
birthYear Stored
getFullName() Derived
getInitials() Derived
getAge() Derived
Edit any stored field above — watch the derived values update automatically, because they recalculate every time. The class only stores 4 values; the other 3 are computed on demand.
Stored Approach (don't do this) redundant
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...
    }
}
Now you have two sources of truth. Every booking has to update both bookedSuites and availableSuites — forget once and the data is wrong.
Derived Approach single source of truth
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;
    }
}
One source of truth: the booked counts. Available is always derived from total minus booked — can't go out of sync.
The Module 2 hotel-operations exercise asks for exactly this — getAvailableSuites() and getAvailableRooms() should be derived getters with no backing variable.
← KNOW vs DO Responsibilities Boolean Getters →