2.5.7 Defining and Using Private Methods

Defining and Using Private Methods

Player can expose RecordTurn while keeping the small operation that updates its count private. Callers need the action, not every implementation step.

Define and call an internal helper
Soccer example
public class Player
{
    private int numberOfTurns;

    public void RecordTurn()
    {
        this.IncreaseTurnCount();
    }

    private void IncreaseTurnCount()
    {
        this.numberOfTurns = this.numberOfTurns + 1;
    }

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

RecordTurn calls the helper on the same Player. The helper reads the existing count, adds 1, and stores it. When it finishes, control returns to RecordTurn and then its caller. This small version has no turn-limit check yet.

Follow one object through the calls

Run these statements inside an outside method.

Use the public entry point
Player jordan = new Player();
jordan.RecordTurn();
jordan.RecordTurn();
int turns = jordan.GetNumberOfTurns();
Count changes
Moment Count
After creation 0
After first RecordTurn 1
After second RecordTurn 2
Apply the idea
Check your understanding