In my previous post I used the Law of Demeter as a motivation for the Hide Delegate refactoring:
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 getManager()
method.
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 Employee
. Yuck.
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.
One thought on “The Law of Demeter”