The Law of Demeter: Context Matters

It’s funny, everyone knows the Law of Demeter, but everyone still seems to think it’s about dots.  There seem to be a million definitions of it, but here’s mine:

Don’t pass in the wrong object.

Laying down the law

Now, Derick’s saying extension methods don’t count.  I’d go further: they don’t matter at all.  The Law of Demeter has nothing to do with how you get an object, just whether or not you started with the right object.  Derick shows some code that is described as making Demeter scream.  (It’s a projection from a variable “assets” to “asset”.)  He shows a version of the code that looks completely different and argues that if that code is okay, so is the original code.  That’s completely correct, but neither has told us anything about whether or not “assets” was the right parameter to the function in the first place.  Here’s the mental rules of thumb:

  • Is “assets” used anywhere in the function other than to generate “asset”?
  • If not, is the principal purpose of the function to return “asset”?

If the answer to the first question is yes, then the function properly depends upon assets and Demeter is happy.  Equally, if the function is a principally a projection or an overload, there’s not a problem: assets is still the correct subject and asset is the result.  It’s when you answer “no” to both questions that you’ve got a problem.  In other words, you’ve violated SRP: the function now projects “assets” to “asset” and then does something else with asset.

If you think of it from a testing perspective, you can apply a different measure.  If you were writing tests for this code, would you start to get annoyed at having to construct the list of assets each time?  If most of your tests had only one item in the list, that’s a bad sign.  So, in answer to Derick’s basic question (does the code violate LoD?) I’d have to answer: I don’t know, I need to see the rest of the code.

Published by

Julian Birch

Full time dad, does a bit of coding on the side.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s