Law of Demeter
Introduction
Let us do some imagination! Thinking….thinking…, Imagine a train on a move that consists of a series of vehicles connected together if a vehicle in the middle breaks, the train will ultimately not reach the destination as expected. Analogous to that, in programming when you intertwine different objects together in a module to achieve a certain functionality you are a step closer to wreak havoc on the entire module in case of failure to at least one object in the connection.
What is the law of Demeter (LoD)?
The Law of Demeter also known as the principle of least knowledge is a design guideline in software development mostly in Object-Oriented Paradigms. It states that a module should not have the knowledge of the inner details of the objects it manipulates. In other words, objects should not reveal their internal implementations to other objects which violates the overall need for abstraction in OOP.
There are different analogies that clearly describe the law of Demeter
Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
“Don’t talk to strangers. Only talk to your immediate friends“
Why is it important?
Obeying the Law of Demeter leads to a more maintainable, testable, robust codebase or modules because it reduces coupling (a degree of interdependence between modules, it measures how modules are bonded to others through dependencies).
Train wreck problem
When this law is not obeyed, there is a risk of facing a problem comparable to a train wreck, i.e if there is an error or change of implementation in method/object/module that is chained together with others, it will lead to the wreckage of the system in different parts.
When to know that you’ve violated the law of Demeter.
When you write statements that Ask rather than Tell you are on the journey of violating the LoD. This does not hold true to methods of the same object
Example
Violates LoD
Line 30 indicates the violation of the law of Demeter because it exposes the implementation of the Board’s print_board method.
play method in the game class asks the Player object to ask the Board object to print_the board
This highlights that our design is not good
Obey LoD
added a player object method to print_its_own_board
This statement doesn’t violate the law of Demeter because it is working on the same String object
References:
https://en.wikipedia.org/wiki/Law_of_Demeter
https://www.infoworld.com/article/3136224/demystifying-the-law-of-demeter-principle.html#:~:text=The%20Law%20of%20Demeter%20principle%20states%20that%20a%20module%20should,of%20other%20objects%20or%20components.