Beginner LevelSoftware Engineering Principles
What is the Law of Demeter (Principle of Least Knowledge)?
❓ Interview Prompt: Explain the Law of Demeter, avoiding dot-chaining (`a.getB().getC().doAction()`), reducing class coupling, and method delegation.
The Law of Demeter (Principle of Least Knowledge) states that a object should only talk to its immediate neighbors and know nothing about the internal details of secondary objects:
Rule of Thumb:
Avoid long method chaining ('customer.getWallet().getCard().charge()'). A method 'M' of object 'A' should only call methods on:
1
Object 'A' itself.
2
Parameters passed into 'M'.
3
Objects created within 'M'.
4
Direct instance fields of 'A'.
Code Implementation Example
typescript
// ❌ Violating Law of Demeter (Train Wreck method chaining)
// user.getAccount().getBillingAddress().getZipCode();
// ✅ Adhering to Law of Demeter (Delegation)
class User {
private account: Account;
getBillingZipCode(): string {
return this.account.getZipCode(); // Delegate query internally!
}
}💡Refactoring train-wreck method chains to respect the Law of Demeter.
🎯 Interview Key Takeaway
Adhere to the Law of Demeter by talking only to immediate friends to prevent tight structural coupling.
#Law of Demeter#Coupling#OOP#Beginner
Back to all Software Engineering Principles Questions→