QA
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.

More Software Engineering Principles Interview Questions

Beginner LevelSoftware Engineering Principles

Explain the 5 SOLID Principles of Object-Oriented Software Design with practical refactoring examples.

Beginner LevelSoftware Engineering Principles

What are DRY (Don't Repeat Yourself), KISS (Keep It Simple, Stupid), and YAGNI (You Aren't Gonna Need It)?

Beginner LevelSoftware Engineering Principles

Why is Composition Over Inheritance a fundamental object-oriented design principle?