Law Of Demeter: Extension Methods Don’t Count


We all know the Law of Demeter, right? It’s the principle that says “don’t let the paperboy reach into your wallet when he wants to be paid. It’s your wallet, you decide what form of payment and how much without letting him have access to the contents of your wallet.”

A couple of days ago, a coworker told me to use this code for a specific situation:

   1: var asset = assets.FirstOrDefault().As<RecordUniqueAsset>();

</div> </div>

He immediately followed that with a statement about Demeter screaming at him.

It occurred to me at that point, that extension methods are just syntax sugar on top of what would otherwise take 10 or 15 lines of code and they don’t really count in the Law Of Demeter evaluation. Extension methods are typically just nice wrappers to help cut down on repeated code. For example, the “As” extension method in this snippet is one that we wrote to cast an object as the specified type (ignore how simple this extension is. it has it’s usefulness in some specific scenarios). Other extension methods that I write tend to be a little more involved, but still have the same basic idea behind them: take 4 or 5 lines of code that I use a lot and make it DRY.

With that in mind, I say this:

   1: var asset = null;

   2: if (assets != null && assets.Count > 0)

   3:     asset = assets[0] as RecordUniqueAsset;

</div> </div>

is the same as the first code snippet in functionality and intent. The extension methods just makes it prettier, and does not violate the Law of Demeter.

There probably are scenarios where the implementation of an extension method would violate LoD and thus the extension itself would… but for the simple scenario extension methods like this… I’m not convinced they violate LoD. What do you think? Does it violate LoD? If so, why? … and I’m also wondering if there are any similar constructs in other languages that would fall under the same exception.

I Want Assert.NotYetImplemented(); In .NET Test Frameworks