Journeys in OOP Design — The Goddess of Cereal Grains
In this installment of the series, I’d like to speak about what is known as the Law of Demeter (LoD), named after a Greek goddess who apparently symbolized something to do with bottom-up design to the folks of the Demeter Project from which it got its name.
A big part of good OOP design has to do with what we might call “loose-coupling”. If I have a bunch of objects, I don’t want them to have to know lots of specific stuff about each other. If you imagine a bunch of circled names on a white-board with arrows between them, these could be your objects and the messages (i.e. method calls) they send to each other. If arrows are going all over the place, including to “far-away” objects, that means there’s a lot of tight coupling going on. Objects are tightly coupled to each other because they are relying on specific implementation details that are particular to the way you have constructed your application.
The obvious reason why this is bad is because, being tightly dependent on a specific technical implementation, your code will not be reusable without lots of context. We want modular code that is “plug and play”, not abstruse spaghetti with a huge back-story.
Another way to describe the wild-arrows-all-over-the-whiteboard-syndrome is that objects are taking it upon themselves to know how to find the resources they need. This is why the law of Demeter is sometimes paraphrased as “use only one dot.” Writing “auto_shop.parts_supplier.whole_sale_supplier.volvo_rep.boss.manufacturing_rep.send_part_request” involves a lot of knowledge about how to get this Volvo part in the context of the application. If something changes in “volvo_rep”, there may be consequences that cascade far away to unrelated objects, creating bugs that are hard to fix. Much better would be if it simply knew what it needs and trusts it’s immediate neighbor to handle the rest, e.g. auto_shop.repair(my_volvo).
The law of demeter is not really a law, it’s a design guideline. Any simplistic requirement like “use only one dot” would obviously be impractical and artifical. As with all guidelines, it is up to the disgression of the programmer to decide when and how to apply it given a particular context. But whatever level you’re at, you can start to use it as a useful way to critique your application, and as a potential signal to loosen up the bonds between your objects, thus making your code more reusable, maintainable and understandable.