The Law of Demeter: Explained To Anyone (OOP)
A module shouldn’t know about the innards of the objects it manipulates 💻
Reading the legendary book of programming “Clean code”, I found this law, that I going to explain to us 😀.
This law were made to improve of software systems, it is exclusivily to Object-oriented-programing
In the head of this article it is mentiones, but…
What it mean? 🤔
Well, we know that objects hide their data and expose functions to interact with the outside. But sometimes we don’t keep it
Let’s start with the example 👀
We started to define our class and instanced it
Then whether we want to get the owner’s name, might we do this:
This kind of code is called a train wreck because it look like a bunch of coupled train cars. This would be the same as:
That is it works?… Yeah, but are bad coding practice and It’s must be avoided.
Why is bad coding practice? ❌
Because we are breaking one principal essence of Object-oriented-programing, what is hide our data. In this case we showed the object’s innards to module which is manipulating the object.
Let’s enumerate the steps:
1- The function “owner()” return the object “Homer”
2- The module must call to “name()” that it return the value that we want
We are accessing to an object one level lower than the object we were manipulating previusly. In conclusion we are showing more information than necessary
The system maintenance will be more difficult
Let’s imagine that we want to do refactor to our code, specifically to object “Owner”
How we see, we changed the functions that return the owner’s name, because also we changed the private variables to “firstName” and “lastName”
For this reason the code will must be refactored
This is unmaintainable, every call will must be refactored and this is very expensive
How to fix this? 🛠
Instead of digging deeply the object in the call, we might do that the object we call return to us all the data we want 😁
Or, adding “firstName()” and “lastName()”
In both cases the call will be the same
Now the maintenance of system is easier than before 🎉🎉
This law also have another phrase that say
“Only talk to your immediate friends and don’t talk to strangers.”
What it previusly said is what we did, we shared it with inmediate friends (with the class) and don’t talk to strangers (we don’t let them look inside the object)
“The Law of Demeter” is useful to maintain of system software and to protect the principles of Object-oriented-programming. I invite you to use it and read the book “Clean Code”, an amazing book ❤.
Thanks to read until the end! 😁👏👏