Message Chains


Symptoms

  • You see calls of the form:

     a.b().c().d() 

    (This may happen directly or through intermediate results.)

Causes

An object must cooperate with other objects to get things done, and that is OK; the problem is that this couples both the objects and the path to get to them. This sort of coupling goes against two maxims of object-oriented programming: Tell, Don't Ask and the Law of Demeter . Tell, Don't Ask says that, instead of asking for objects so that you can manipulate them, you simply tell them to do the manipulation for you. It's phrased even more clearly in the Law of Demeter: A method shouldn't talk to strangers; that is, it should talk only to itself, its arguments, its own fields, or the objects it creates. (Andrew Hunt and David Thomas's The Pragmatic Programmer describes both of these rules in more detail.)

What to Do

  • If the manipulations actually belong on the target object (the one at the end of the chain), use Extract Method and Move Method to put them there.

  • Use Hide Delegate to make the method depend on one object only. (So, rather than a.b().c().d() , put a d() method on the a object. That may require adding a d() method to the b() and c() objects as well.)

Payoff

May reduce or expose duplication.

Contraindications

This is a trade-off refactoring. If you apply Hide Delegate too much, you get to the point where everything's so busy delegating that nothing seems to be doing any actual work. Sometimes, it's just easier and less confusing to call a small chain.



Refactoring Workbook
Refactoring Workbook
ISBN: 0321109295
EAN: 2147483647
Year: 2003
Pages: 146

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net