2.5.11 Preventing Invalid Object State

Preventing Invalid Object State

A training area tracks a practice temperature. For this simplified application, it starts at 20.0 and accepts half-degree changes only within 15.0 through 25.0 inclusive.

Check a proposal before storing it
Soccer example
public class TrainingArea
{
    private double temperature = 20.0;

    public double GetTemperature()
    {
        return this.temperature;
    }

    public void IncreaseTemperature()
    {
        this.ChangeTemperature(0.5);
    }

    public void DecreaseTemperature()
    {
        this.ChangeTemperature(-0.5);
    }

    private void ChangeTemperature(double change)
    {
        double proposedTemperature = this.temperature + change;

        if (proposedTemperature >= 15.0 && proposedTemperature <= 25.0)
        {
            this.temperature = proposedTemperature;
        }
    }
}

Both public actions use the same private helper. It calculates a proposal first. Only a proposal within both bounds replaces the field. A rejected proposal leaves the previous value untouched.

Check the endpoints and the next step
Independent cases
Stored value before Action Proposed value Stored value after
20.0 Increase 20.5 20.5
24.5 Increase 25.0 25.0
25.0 Increase 25.5 25.0
15.0 Decrease 14.5 15.0

Starting fresh, ten increases reach 25.0; the eleventh changes nothing. Ten decreases from a fresh area reach 15.0. These rules illustrate validation; they are not guidance about real training conditions.

Apply the idea
Check your understanding