Refactoring Workbook

Symptoms

  • One class accesses internal (should-be-private) parts of another class. (There is a related form of Inappropriate Intimacy between a subclass and its parents; see "Inappropriate Intimacy [Subclass Form]," Chapter 9.)

Causes

The two classes probably became intertwined a little at a time. By the time you realize there's a problem, they're coupled . There may be a missing class that should mediate between them. This problem is more serious between unrelated classes than between a parent and child.

What to Do

  • If two independent classes are entangled, use Move Method and Move Field to put the right pieces on the right class.

  • If the tangled part seems to be a missing class, use Extract Class and Hide Delegate to introduce the new class.

  • If classes point to each other, use Change Bidirectional Reference to Unidirectional to turn it into a one-way dependency.

  • If a subclass is too coupled to its parent (as explained in "Inappropriate Intimacy [Subclass Form]," Chapter 9)

    • If the subclass is accessing the parent's fields in an uncontrolled way, use Self Encapsulate Field.

    • If the parent can define a general algorithm that the children can plug into, then use Form Template Method.

    • If the parent and child need to be even more decoupled, then Replace Inheritance with Delegation .

Payoff

Reduces duplication. Often improves communication. May reduce size.

Contraindications

None identified.

Категории