2.5.4 Analyzing Encapsulation Problems and Unnecessary Coupling

Analyzing Encapsulation Problems and Unnecessary Coupling

The coach window currently knows how the Wildcats objects store their information. Examine that dependency before changing any declarations.

Identify the owner and the caller

These statements belong inside an existing window method. For this intentionally exposed starting design, Team has a public Players list and Player has a public NumberOfTurns field. Assume the list contains Jordan at index 0.

Existing design to critique
team.Players[0].NumberOfTurns = -2;
team.Players.Clear();
Questions to ask
Statement Design concern
Assign -2 to NumberOfTurns The caller bypasses the nonnegative-count rule
Clear Players The caller can erase the roster without Team deciding whether that is allowed
Look beyond the number of dots

If Team changes its storage, window code that indexes Players may need revision. If the turn rule changes, every direct writer must be examined. A long access chain can reveal these dependencies, but a dot count alone does not establish a defect.

Start by hiding helpers and configuration with no outside users. Then replace required outside access with purposeful requests and queries. Keep required behavior available.

Apply the idea
Check your understanding