Hi devs :)
Recently, I’ve been thinking a lot about the Law of Demeter, also known as the Principle of Least Knowledge. It’s one of those principles in object-oriented programming that makes total sense once you understand it, but it’s easy to overlook in day-to-day coding.
So, What’s the Law of Demeter?
In simple terms, the Law of Demeter says that each object should know as little as possible about other objects. Basically, an object should only interact with its immediate "friends" — the objects it directly holds references to — rather than trying to navigate through a web of dependencies.
Think of it like this: If you’re friends with someone, you might know their contact info, but you don’t need to know their entire family tree or their friend-of-a-friend’s details. It’s about minimizing dependencies, which in turn reduces complexity and improves maintainability.
Why Should You Care?
The real benefit of the Law of Demeter is that it helps decouple objects in your code. When you avoid chaining multiple calls together, your objects become less reliant on the internal structure of others. This makes your code more resilient to changes. If something deep down the chain changes, it doesn’t break the entire system.
For example, instead of this:
salary = employee.get_department().get_manager().get_salary()
It’s better to do something like this:
salary = employee.get_manager_salary()
This way, if the structure of Department
or Manager
changes, you’re not as likely to have issues in your Employee
class.
When to Apply It?
Now, I’m not saying you need to follow the Law of Demeter obsessively in every single line of code. But I’ve found that being mindful of it helps prevent unnecessary complexity, especially as projects grow. For me, the Law of Demeter is less about following a strict rule and more about designing software that’s easier to understand, maintain, and evolve over time.
That’s my take on the Law of Demeter. What about you? Do you think about this principle when designing your classes? Let me know your thoughts!
Top comments (0)