Dont Confuse Your Dog

A variation (or re-stating) of TellDontAsk.

In the discussion on the LawOfDemeter, MichaelFeathers offers the analogy, "If you want your dog to run, do you talk [to] your dog or to each leg? Further, should you be able to manipulate the dog's leg without it knowing about it? What if your dog wants to move its leg and it doesn't know how you left it? You can really confuse your dog."

The moral: Change the state of a contained object only through the containing object's interface.

"Aha!" you say. "If I employ the technique of encapsulation, then a method won't even know of the existence of any contained objects."

That's precisely the point. To walk your dog, you don't need to know of the existence of its legs. (And in fact, dogs with fewer than four legs can go for walks. There is even a case of a dog whose hindquarters rested on a little carriage; its "walk" method employed two legs and two wheels (these latter, one hopes, encapsulated within a "carriage" interface).)

Something about telling the milk to uncow itself...? The LawOfDemeter is stronger and more controversial, as it prohibits a method from invoking any method of an object contained by an object known to the method, not just those methods that change the contained object's state.

(None of this adds anything to the discussion on the LawOfDemeter, but don't you agree that it's a pithier title?)

This is akin to telling the right person what you want to have happen, not how to do it. This is a basic tenet of encapsulation -- I don't need to know how you walk for you to walk for me. Hence, I don't even need to know how many legs you have, let alone talk to them directly; it breaks "good" encapsulation.

Now, obviously, if I'm a podiatrist, my relationship with your legs is different.

The podiatrist is the debugger.

This approach to encapsulation is also part of what makes for effective management of people, and is why MicroManagement tends to cause more problems than it fixes.

EditText of this page (last edited January 10, 2011) or FindPage with title or text search