2.7.7 Introduction to Immutable Objects

Introduction to Immutable Objects

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.

Create a stable result object
Soccer example
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.

Check the whole design

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.

TrainingResult stores readonly round and goals integers initialized by its constructor and exposes only getter properties.
A result with no state-changing interface
Different promises
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
Represent a correction with a new result
Correct a recorded result
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.

Apply the idea
Check your understanding