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.
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.
| 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.