Take the 2-minute tour ×

When is it ok to break "the law of demeter"? Any examples??

share|improve this question

closed as not constructive by Gordon, ircmaxell, PeeHaa, tereško, hakre Apr 24 '12 at 18:59


This question, and subsequent answers, would be a lot more useful if you could give a brief explanation of "the law of demeter"... –  GregD Jan 27 '09 at 18:15
@GregD, just added a link for you. –  Rob Wells Jan 27 '09 at 18:29
add comment

11 Answers

up vote 20 down vote accepted

It's okay to break any rule when you understand the consequences and are willing to either deal with the fallout or fix it. Usually that means living with it forever until you get fired or quit or refactor.

Usually people break rules without understanding higher goals or a more global context. That's when it is bad. Unfortunately, it takes discipline and experience to not break rules unnecessarily, and experience is not contagious.

share|improve this answer
This is a good answer but it could be improved with a description of the consequences of breaking the Law of Demeter. –  Phineas May 25 '11 at 23:11
add comment

At some point in my career the pragmatic businessman in me started to have serious issues with the pragmatic programmer in me.

The sad truth is: If you are spending time worrying about The Law of Demeter, you are more than likely just wasting time/money. It's a good academic exercise, but only good in practice for a very limited subset of real world projects where attention to that level of design detail really matters.

Get it done, get it out the door, use it to generate revenue (monetary or otherwise). Any problems associated with the lack of adherence to The Law of Demeter can be filed under "problems I hope to have some day".

In short, almost always

share|improve this answer
add comment

Whenever it makes your code more readable / maintainable. The Law of Demeter is (IMHO) somewhat schizophrenic. On the one hand, it is extremely detailed. On the other hand, it's only a very general rule because in many contexts it simply doesn't apply. Method chaining may actually be a good thing. Consider the following builder class application (notice that in this code, each method actually returns a different type so this code violates the Law of Demeter).

Date date = Date.year(2009).month(1).day(1);

First, what are the advantages of such a pattern over the following construct?

Date date = new Date(2009, 1, 1);
  • It improves readability,
  • It improves compile-time type safety, and
  • It allows Date very easily to be an immutable class which in itself has a lot of advantages.

Now, applying the Law of Demeter would yield code that is (again, IMHO) neither as readable nor as maintainable and simply offers not a single advantage over the terse form.

DateYearProxy y = Date.year(2009);
DateMonthProxy m = y.month(1);
Date date = m.day(1);


share|improve this answer
Your example isn't breaking the Law, is it? The Law is about calling methods down the hierarchy, not about chaining methods at one level of the hierarchy. That is, if month was a sub-class of Date, and day a sub-class of month within Date, then it would break the Law, but as it stands, it is fine. –  Jonathan Leffler Jan 27 '09 at 18:56
A C++ example: cout << "abc" << i << "def"; Not breaking the law - but is chaining methods. –  Jonathan Leffler Jan 27 '09 at 18:57
@Jonathan: I might have always understood the LoD wrong, then. But I don't think so. No definitions that I know restrict themselves to subtypes. See also the German Wikipedia article, it gives an example equivalent to mine. –  Konrad Rudolph Jan 27 '09 at 19:04
@Konrad: 300 characters ain't gonna be enough! I've gone to the LoD Wikipedia page, and is says "one dot". It also has a detailed list of 4 criteria, and I'd have thought that "one dot" was an over-simplification of the 4 criteria. It also says there is debate about the approach. –  Jonathan Leffler Jan 28 '09 at 22:36
-1 Method chaining doesn't break the LoD just because you have more than one dot per line. Each method is part of the same class. I prefer immutability but for some classes, like Java's ByteBuffer, chaining just makes things cleaner. –  Outlaw Programmer Jan 29 '09 at 4:20
show 12 more comments

it's not ok. ever. That's why it's the Law of Demeter, not the suggestion of Demeter.

Violators will be prosecuted. ;-)

share|improve this answer
sigh - no sense of humor! –  Steven A. Lowe Jan 28 '09 at 6:10
I feel your pain Steven. –  gnovice Jan 29 '09 at 4:30
lol - cant believe this was down voted. –  Greg Dean Jan 29 '09 at 4:54
add comment

This is a hard question. Basically the law of demeter is more a convention than a strict rule. It is true that following it allows for a better OOP and results in a more decoupled code. In my experience, it's common to break this rule when you're working with User Interfaces. If you're creating your system from scratch, it's easier to attend this rule. Remember that like design patterns, this rule is not an absolute.

share|improve this answer
add comment

The only programming law I follow is KISS (Keep It Simple, Stupid or i prefer to call it, Keep it simply stupid).

At the end of the day what really matters is that: 1 - The software works. 2 - No bugs in it (or as minimal as possible) 3 - Your code is easy to read/understand and easy to modify.

So, I think that you might follow this or that convention, as long as it serves you, not the other way around.

share|improve this answer
-1 I disagree with this because, if you follow the law of demeter, you make your design slightly more complex (remove public field, add a method). You reduce coupling but wind up with more code/indirection. –  Outlaw Programmer Jan 27 '09 at 18:34
If KISS is your only law, you might like this: thedailywtf.com/Articles/FrontAhead-Design.aspx :-) –  Daniel Rikowski Jan 27 '09 at 19:06
+1 for the three points you mentioned in your second paragraph, and for your conclusion. –  e.James Jan 27 '09 at 20:32
KISS = Keep It Surreal, Sergio! –  Steven A. Lowe Jan 27 '09 at 22:00
I also must state that i am a perfectionist. While my first priority is to keep my code simple and easy to maintain i also try to write the best code possible, as long as it makes sense. –  Sergio Jan 29 '09 at 10:11
show 1 more comment

Sorry to say but this is one law I had never heard of until this post and I don't think it is particularly widely followed in the programming community.

The wikipedia article wrote:


I don't see any reference here to the rule being followed in the agile community, in the most influential language design groups or any place else besides Northeastern University, illustrious school though it may be.

For example, on the c2 website, someone wrote

Before reading further please see LawOfDemeterVsInformationHiding, LawOfDemeterMakesUnitTestsEasier, LawOfDemeterIsHardToUnderstand, LawOfDemeterIsTooRestrictive, LawOfDemeterAndCoupling.

share|improve this answer
Did you read the whole article? I didn't understand the law correctly until I did. See in particular the "More formally..." section. –  Kyralessa Jan 29 '09 at 5:10
add comment

One case I've hit a few times where it would simply make a huge amount of stupid code:

Classes whose purpose is to round up a bunch of elements into some entity, say a customer's order.

Ok, there's an object in there for customer information. There's also one for the graphics. (CAD/CAM system) There's a third holding subdivisions in the order and these contain a fourth that are actually descriptions of the objects involved.

On the CAD side of things the descriptions of how to build the objects have virtually no effect outside the pricing engine--the rest of the program almost totally ignores the groups and works on the list of individual objects.

Note that these various data elements are virtually independent of each other, the top level container exists because there are cases where multiple plans can be loaded and the top level object contains things like I/O routines etc.

To provide routines to drill down into the various objects would be a huge waste of code. Many of the routines deal only with a smaller object and thus don't run afoul of the LoD but there are many cases where you simply need one piece of data that a couple of layers down--to provide ways around this would probably add 10k of code for no benefit other than complying with the LoD.

share|improve this answer
add comment

Ahh, the "occasionally useful suggestion of Demeter". (Martin Fowler.)

I think DIE/DRY and normalization are more fundamental principles, but it's ultimately going to be a contest between conflicting guidelines that you will need to apply common sense to.

The "law" applied to object classes in one specific project and does have obvious value as a class hierarchy design model.

But there is controversy over Demeter's application specifically with respect to Rails views. By definition they are a report, and so it is questionable whether the Suggestion of Demeter is applicable. I suspect this is true in many other situations.

share|improve this answer
add comment

In the shop I work at, the Law of Demeter is not even discussed. It doesn't exist.

We have a kind of intermediate API called ObjectLayer (dumb name but its stuck) that hosts the Object-Relational mapping. It uses lots of public properties, etc. It serves as the Model part of MVC. Part of the controller is grafted into ObjectLayer because it is programmable by the end user and needs to work on an alternate interface.

The GUI objects have references to the objects in ObjectLayer. These are passed around, manipulated almost at will, etc by the controller code attached to the GUI.

The mini-programming language is the only truly stable part of the interface. ObjectLayer stabalized in its form almost by accident because it works really well until someone tries to change it (not that the code is bad but half the developers have difficulty writing truly reusable code).

share|improve this answer
add comment

Suppose you have this:

function(foo) {
   // ...

then if you also


in the same function then maybe it's not too bad.

However, clearly if you never do anything with foo, but only use it to get to fooBar, then breaking the law is bad.

Another variation of the law is "don't look for things, ask for them". (Asking for them means "require them as arguments").

See here for a good discussion.

share|improve this answer
add comment
