Does anybody have any exercises for practicing Law of Demeter?

Hi there

I’ve been trying to get into the habit of not flagging LoD violations in code reviews based on the number of methods called on an object, the old “2 dots” rule (a.method.another_method).

So I’m looking for some code exercises that will help me learn the spirit of the law and teach the rest of my team.

Any ideas? Maybe it could be an exercise @benorenstein?

Thanks :smile:

Good idea!

It might be a little difficult to come up with suitably-complex examples though. I think contrived examples are one of the reasons why Law of Demeter gets seen as the “2 dots rule” in the first place. Avdi’s old blog post on the principle is still a great resource.

@aaronmcadam I think just thinking about having ‘2 dots’ could be misleading just because if you are calling a method that return the same data type like String.gsub.upcase that’s not actually a violation of the law of demeter.

That’s exactly the kind of thing I think having lots of exercises about it would mitigate.

I wish I could share all the crappy Rails code I wrote over the past three years of being self-taught. I have production code that I’m stilling maintaining to this day no doubt rife with LoD violations that I wish I could share, but sadly it’s proprietary :frowning:. I bet the upcase community would have a field day picking it apart.

I’ve heard that once you get really really good at writing solid code it’s kind of difficult to reproduce bad design for the sake of example. I can’t attest to this as I’m still a pretty terrible programmer.

Not sure if it helps, but here’s what rails_best_practices detects as LOD violations on the Upcase repo. All very minor:

1 Like