Software Design/Make function to access its enclosing class more than any of its arguments

From Wikiversity
Jump to navigation Jump to search

Checklist question:

  • A function accesses its enclosing class more frequently than any of its object arguments?

Sometimes a function which accesses one of its object arguments (ArgClass) more than its enclosing class (EnclosingClass) can simply be moved to ArgClass.[1]

At other times, this situation may identify some problem with the decomposition of the state between classes, or with the decomposition of the logic between functions. The parts of the state of ArgClass that are accessed in the subject function may better be moved to EnclosingClass.[2] If the whole state of ArgClass is accessed in the subject function then it might be that ArgClass shouldn't be a separate class and should be merged into EnclosingClass. Alternatively, it may be the case that ArgClass fails to provide a function which computes something based on multiple parts of its state. If such function was available it could have been used in the subject function to reduce the number of accesses to ArgClass.

If locations for all functions in all classes are chosen according to this practice then the classes are generally more loosely coupled and it's likely that visibility of some members (fields and functions) of some of the classes could be narrower which makes these classes easier to change. See practice Minimize the accessibility of classes and members.

Why not

[edit | edit source]

Implementations of Visitor pattern, Kent Beck's Self Delegation pattern,[3] and, in some instances, of Strategy pattern are exempt from following this practice. However, all these patterns aim at the same goal of making the change easier by localizing it and thus reducing the change amplification. These patterns are used in the situations when the general rule of thumb that the data and the logic that references that data change together is not the case.[1]

[edit | edit source]


[edit | edit source]
  1. 1.0 1.1 Refactoring: Improving the Design of Existing Code (2 ed.). 2018. ISBN 978-0134757599.  Chapter 3, "Feature Envy" section
  2. Refactoring: Improving the Design of Existing Code (2 ed.). 2018. ISBN 978-0134757599.  Chapter 3, "Insider Trading" section
  3. Smalltalk Best Practice Patterns. 1996. ISBN 978-0134769042.  Chapter 3, "Self Delegation" section