The Law of Demeter for functions requires that a method M of an object O may only invoke the methods of the following kinds of objects:
- O itself
- M’s parameters
- any objects created/instantiated within M
- O’s direct component objects
Code that violates the Law of Demeter is a candidate for Hide Delegate, e.g.
manager = john.getDepartment().getManager() can be refactored to
manager = john.getManager(), where the
Employee class gets a new
However, not all such refactorings make as much sense. Consider, for example, someone who’s trying to kiss up to his boss:
sendFlowers(john.getManager().getSpouse()). Applying Hide Delegate here would yield a
getManagersSpouse() method in
I have a couple of problems this use of Hide Delegate. First of all, it creates methods that by definition reek of feature envy. Second, methods like
getManagersSpouse() clearly violate the single responsibility principle. Finally, the Law of Demeter clashes with the concept of fluent interfaces.
Luckily, you can always back out from an adverse Hide Delegate by applying the opposite refactoring: Remove Middle Man.