Law of Demeter
The Law of Demeter describes a specific form of Loose Coupling. It can be summarized like this:
- Each unit should have only limited knowledge about other units: only units “closely” related to the current unit.
- Each unit should only talk to its friends; don’t talk to strangers.
- Only talk to your immediate friends.
Or, differently put:
- A method of an object can call methods of that object
- A method can call a method of its parameters
- A method can call a method of any objects created or instantiated by that method
- A method can call a method of objects that are dependencies of the methods object
- A method can call a method of a global variable (oof) that is accessible by the object of the method
Meaning that classes can call methods on other classes, but should not “reach through” to reach other classes.
Code Example
class InvoiceController {
public function createInvoiceForUser(User $user) {
// code goes here...
$user->getAccount()
->getBalance()
->subtractSum($invoiceTotal);
}
}
This code is a good example for a violation of the LoD because it violates the One Dot Principle. Furthermore, it is tightly coupled, because it means that the InvoiceController has to have knowledge about how the Account and Balance classes work, when it should only call methods on the User object that was passed as an argument.
This creates problems if a User class should have different methods of payment in the future.
A better example would be:
class InvoiceController {
public function createInvoiceForUser(User $user) {
// code goes here...
$user->payInvoice($invoice)
}
}
The User class, then, needs a proxy method to pay:
class User {
public function payInvoice(Invoice $invoice) {
$this->getAccount()->payInvoice($invoice);
}
}
The Account class, then, can check its own balance and subtract the invoice’s sum.
☝️ Backlinks
No notes are currently linking to "Law of Demeter".