Image created with Midjourney. Image prompt: 2d illustration minimal style of A train of simple geometric shapes representing objects A, B, and C moving along a track. Each shape has a speech bubble containing code relevant to its actions. Object A's speech bubble shows it communicating directly with B, but there's a 'no entry' sign on a speech bubble from A to C, symbolizing the Law of Demeter
<aside> 💬 Don't talk to strangers.
</aside>
The Law of Demeter, succinctly put as "Don't talk to strangers," is a potent and practical principle for software development, particularly for object-oriented languages. It advocates for a unit of software to interact only with its immediate collaborators, thereby embodying the "Principle of Least Knowledge"1.
Imagine three objects in your software code – A
, B
, and C
. Object A
has a reference to object B
and can, therefore, call its methods. However, if B
has a reference to object C
, according to the Law of Demeter, A
should not call C's
methods directly. So, if C
has a doThing()
method, A
should not invoke it directly as B.getC().doThis()
1.
Let's delve deeper into this concept with three practical examples:
A
) wants to access the profile picture (C
) of one of his friends (B
). Instead of A
directly accessing B's
profile picture (C
), A
should request B
to provide the profile picture. This way, the privacy controls and data access can be managed at the B
level, keeping A
unaware of the underlying complexities or changes in accessing the profile picture.A
) should be able to place an order (B
) without needing to directly interact with the inventory management system (C
). Instead, the order system (B
) should manage the interaction with the inventory system (C
), keeping the interactions encapsulated and the customer (A
) oblivious to the complexities of the inventory management.A
) should be able to request a document (B
) without having to directly handle the document's storage system (C
). The document object (B
) should abstract the details of the storage system (C
), ensuring that the user (A
) interacts only with its immediate collaborator, the document (B
).The Law of Demeter is not just an abstract principle; it has tangible benefits when building digital software products:
In summary, the Law of Demeter is a guiding principle that promotes cleaner, more maintainable, and more robust software. As software developers, embracing this principle is a step towards creating better digital software products.