📝 This article is an English translation of the original French version available here: https://victor-prdh.com/blog/03-loi-de-demeter.md/
Demeter's Law in PHP: Writing Code That Talks Less… but Better
In software development, we often hear about best practices: decoupling, separation of concerns, SOLID principles… But there is one, sometimes overlooked, that deserves our attention: Demeter's Law. Also known as the principle of least knowledge, it helps write more robust, readable, and maintainable code.
In this article, we will see what it entails, why it is useful, and how to apply it practically in your PHP and Symfony projects.
What is Demeter's Law?
Formulated in the late 1980s at MIT, Demeter's Law is based on a simple idea:
“An object should only talk to its immediate friends, not to the friends of its friends.”
In other words, a class should limit its knowledge of the system. It should only interact with:
- itself (its own methods),
- its direct attributes,
- its method parameters,
- the objects it creates,
- and possibly global objects (like singletons, though these should be avoided).
The goal is to prevent code from being too dependent on the internal structure of other objects.
Example of Demeter Law Violation
Here’s a common example:
$city = $order->getCustomer()->getAddress()->getCity();
Here, to get the city of a customer, the Order object must expose its Customer, which exposes its Address, which exposes its City.
This is what we call the train wreck pattern: a long chain of calls showing that we know far too much about the internal structure of the object.
Corrected Example
A better approach is to delegate responsibility to the appropriate objects:
class Order
{
private Customer $customer;
public function getCustomerCity(): string
{
return $this->customer->getCity();
}
}
Then, usage becomes:
$city = $order->getCustomerCity();
This way, the Order object becomes responsible for how the information is accessed.
If the internal structure of Customer changes tomorrow (for example, if the address is no longer directly linked to the Customer object), the calling code will not be impacted.
Concrete Benefits
Respecting Demeter's Law brings several immediate benefits:
- Robustness: internal changes do not affect calling code.
- Encapsulation: objects hide their internal details.
- Readability: fewer chained calls, code expresses directly what we want.
- Testability: it's easier to test a single method than to simulate a long object chain.
Conclusion
Demeter's Law is a simple but powerful rule: “only talk to your close friends.”
By avoiding excessive chained calls and delegating responsibilities to the right objects, you get code that is:
- clearer,
- more robust,
- easier to maintain.
Take a moment to review your code: how many successive -> calls do you find?
It might be a sign that it's time to apply Demeter's Law.
What about you?
Share your experience or tips with me on LinkedIn — happy to chat!
Top comments (0)