2.5.12 Reducing Direct Field Access

Reducing Direct Field Access

Convert an exposed Player count without leaving callers using a field that no longer exists publicly. Treat the class and its callers as one complete change.

Find every direct reader and writer

In the old version, Player declares a public int NumberOfTurns field. A caller starts at zero and records one turn this way:

Before the conversion
Player jordan = new Player();
jordan.NumberOfTurns = jordan.NumberOfTurns + 1;
int displayedTurns = jordan.NumberOfTurns;

Find All References separates reads from writes. Do not replace a request to record one turn with a method that accepts an arbitrary total.

Replace storage access with a contract

Replace the old Player definition with the complete controlled-access version, which declares private numberOfTurns and provides RecordTurn and GetNumberOfTurns.

After the conversion
Player jordan = new Player();
bool accepted = jordan.RecordTurn();
int displayedTurns = jordan.GetNumberOfTurns();

For the first request, accepted is true and displayedTurns is 1. At the limit, accepted is false. The caller can use that result to decide what feedback to show.

Check behavior and remaining dependencies
  1. Build after changing the class and all its affected callers.
  2. Check the initial count, an accepted request, and a rejected fourth request.
  3. Search for remaining direct uses of the old field.
  4. Confirm that no replacement method returns or exposes the private storage unnecessarily.
Apply the idea
Check your understanding