Demeter’s Law

So, I’m still working my way through The Pragmatic Programmer (yeah, I’ve been busy) and just went through the chapter on Demeter’s Law. I have to say, I’m a little skeptical. The general idea is that you only use objects and methods of objects that your current method(or class) “owns” directly, not things that other objects own. So for example, if your object takes a “Customer” object containing a “Person” object, you should not call Customer.Person.FirstName, because you don’t own the “Person” object. Instead, you should use a wrapper getter in Customer that gets FirstName from Person (CustomerFirstName, say). And if Customer was inside of Order, and you wanted the Customer’s first name from Order, the proper thing to do would be to wrapper the CutomerFirstName up, maybe with BuyerFirstName.

SO, instead of Order.Customer.FirstName

you’d have Order.CustomerFirstName

And THAT you can safely call. What’s the reasoning for this? well, this allows all kinds of changes to Person and FirstName, and once the class is changed in Customer, nobody else needs to know anything happened. since everything else is a wrapper, everything else will just work. Problem? well, Order, instead of being a stripped-down class just dealing with order-related stuff ends up possibly being an enormous class full of Customer and Person wrapper stuff, and depending on what other objects Order has, it could be even worse. Pragmatic suggests dealing with this by using a code generator… Frankly, though I see how coding this way would be safer, the idea of having huge amounts of wrapper crap kinda feels like a smell. Maybe this is worth it, but I’m not quite sold yet on it being worth the clutter. I’m going to have to think about this one a bit more.


Leave a Reply

This blog is kept spam free by WP-SpamFree.