2.5.9 Public Methods as Controlled Access to a Class

Video: Encapsulation, Revisited (15:29)
Public Methods as Controlled Access to a Class

The coach requests one training turn. Player decides whether that transition is allowed and reports whether it accepted the request.

Expose an operation with a clear result
Soccer example
public class Player
{
    private readonly int turnLimit = 3;
    private int numberOfTurns;

    public bool RecordTurn()
    {

        if (this.numberOfTurns < this.turnLimit)
        {
            this.numberOfTurns = this.numberOfTurns + 1;
            return true;
        }

        return false;
    }

    public int GetNumberOfTurns()
    {
        return this.numberOfTurns;
    }
}

A new Player starts with 0 turns. RecordTurn tests the current state before writing. Below 3 it records exactly one turn and returns true. At 3 it skips the assignment and returns false. Returning a result tells the caller whether work happened.

Trace accepted and rejected requests
RecordTurn accepts a request only while numberOfTurns is below turnLimit; a rejected request preserves the count.
A turn request has two outcomes
Repeated requests on one Player
Call Count before Accepted Count after
First 0 true 1
Second 1 true 2
Third 2 true 3
Fourth 3 false 3

GetNumberOfTurns is a query: it reports state without recording a turn. Calling it twice should not consume two turns.

Apply the idea
Check your understanding