2.7.9 Adding Property Accessor Logic to Protect Object State

Adding Property Accessor Logic to Protect Object State

Move the training temperature check into a private setter while keeping the public increase and decrease actions. The accepted range remains 15.0 through 25.0 inclusive.

Validate the proposed absolute value
Soccer example
public class TrainingArea
{
    private double temperature;

    public TrainingArea()
    {
        this.Temperature = 20.0;
    }

    public double Temperature
    {
        get
        {
            return this.temperature;
        }

        private set
        {

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

    public void IncreaseTemperature()
    {
        this.Temperature = this.Temperature + 0.5;
    }

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

In IncreaseTemperature, the right side reads the getter and adds 0.5. Assignment then invokes the setter with the proposed absolute temperature. For a starting value of 20.0, value is 20.5, not 0.5.

Reject before writing the backing field
The Temperature setter stores value only when it is within 15.0 through 25.0 inclusive; other proposals leave state unchanged.
Validate before replacing stored state
Setter cases
Previous field Proposed value Accepted New field
20.0 20.5 Yes 20.5
24.5 25.0 Yes 25.0
25.0 25.5 No 25.0
15.0 14.5 No 15.0

This preserves the behavior of the earlier private-helper design. The constructor also uses the property; its valid 20.0 assignment passes the same check.

Apply the idea
Check your understanding