The Law of Demeter is not really a law, but specifies a style guideline: never call a method on an object received from another call. The code that follows this guideline is easier to maintain, adapt, and refactor, has less coupling between methods, less duplication, and better information hiding. On the other hand, you may need to write many wrapper methods to meet this guideline.
Example:
boolean pay(Customer c, Invoice invoice) {
int dollars = c.getWallet().getDollars(); // violation
if (dollars >= invoice.getAmount()) {
Wallet w = c.getWallet();
w.subtract(invoice.getAmount()); // violation
return true;
}
return false;
}
The above example might be better implemented as a method payInvoice(Invoice invoice)
in Customer
.
Example:
Engine engine = car.getEngine();
int cylinders = engine.getNumberOfCylinders();