A completed training result can be a stable record: once created, its round number and goal count never change. That is a stronger promise than exposing a getter-only view of changing state.
public class TrainingResult
{
private readonly int round;
private readonly int goals;
public TrainingResult(int round, int goals)
{
this.round = round;
this.goals = goals;
}
public int Round
{
get
{
return this.round;
}
}
public int Goals
{
get
{
return this.goals;
}
}
}For this example assume a positive round and nonnegative goals. Both fields store integer values, are initialized by the constructor, and cannot be reassigned by ordinary methods. The public interface offers no state-changing operation.
Player with a getter-only NumberOfTurns is still mutable because RecordTurn changes it. TrainingResult has no corresponding change operation. A readonly field containing a mutable list would also need further examination.
| Design | What it guarantees |
|---|---|
| Private field | Outside code cannot directly access that field |
| Readonly field | Ordinary methods cannot replace its stored value or reference |
| Getter-only property | Callers cannot assign through that property |
| Immutable object design | Its state does not change after creation |
TrainingResult result = new TrainingResult(1, 2);
TrainingResult original = result;
result = new TrainingResult(1, 3);The variable result now reaches a new object with 3 goals. original still reaches the first object with 2 goals. Replacing a variable reference did not modify the first result.