Bird
Raised Fist0
LLDsystem_design~15 mins

Law of Demeter in LLD - Deep Dive

Choose your learning style10 modes available
Overview - Law of Demeter
What is it?
The Law of Demeter is a design guideline for writing software that limits how much one part of a program knows about other parts. It says that a module should only talk to its immediate friends, not friends of friends. This helps keep code simple and easier to change. It is sometimes called the principle of least knowledge.
Why it matters
Without this rule, code becomes tightly connected and hard to fix or improve because changes in one place ripple everywhere. Imagine a machine where every part depends on many others; if one breaks, the whole stops. The Law of Demeter helps avoid this by keeping parts independent and easier to manage.
Where it fits
Before learning this, you should understand basic programming concepts like functions, objects, and modules. After this, you can learn about design patterns and software architecture principles that build on keeping code clean and modular.
Mental Model
Core Idea
Each part of a program should only communicate directly with its immediate neighbors, not with distant parts.
Think of it like...
It's like talking only to your close friends instead of asking your friend's friends for information. This keeps conversations simple and avoids confusion.
┌─────────────┐
│   Module A  │
└─────┬───────┘
      │ talks only to
┌─────▼───────┐
│   Module B  │
└─────────────┘

Module A should NOT talk to Module C, which is a friend of Module B.
Build-Up - 6 Steps
1
FoundationUnderstanding Module Communication Basics
🤔
Concept: Modules or parts of a program communicate by calling each other's functions or methods.
In programming, a module is a piece of code that does a specific job. Modules often need to ask other modules for information or actions. For example, a user interface module might ask a database module for data.
Result
You see that modules depend on each other to work together.
Understanding how modules talk is the first step to controlling and improving their connections.
2
FoundationWhat is Coupling Between Modules
🤔
Concept: Coupling means how much one module depends on another. Less coupling means modules are more independent.
If Module A needs to know many details about Module B, they are tightly coupled. This makes changes risky because changing B might break A. Loose coupling means modules only know what they need to, making the system flexible.
Result
You recognize that tight coupling can cause problems in software maintenance.
Knowing about coupling helps you see why limiting knowledge between modules is important.
3
IntermediateIntroducing the Law of Demeter
🤔Before reading on: do you think a module should access data from any other module it can reach, or only from its direct connections? Commit to your answer.
Concept: The Law of Demeter says a module should only talk to its immediate friends, not friends of friends.
This means a module should only call methods of: - Itself - Its parameters - Any objects it creates - Its direct components It should NOT call methods on objects returned by other calls (no chaining).
Result
You learn a clear rule to reduce coupling and improve code clarity.
Understanding this rule helps prevent complex chains of dependencies that make code fragile.
4
IntermediateApplying Law of Demeter in Code
🤔Before reading on: do you think chaining method calls like a.getB().getC().doSomething() follows the Law of Demeter? Commit to yes or no.
Concept: Method chaining often breaks the Law of Demeter because it reaches beyond immediate friends.
For example, instead of writing a.getB().getC().doSomething(), you should add a method in B like b.doSomethingOnC() and call a.getB().doSomethingOnC(). This keeps calls local and hides internal details.
Result
You see how to rewrite code to follow the Law of Demeter.
Knowing how to refactor code to avoid deep chains improves maintainability and reduces bugs.
5
AdvancedBenefits and Tradeoffs of Law of Demeter
🤔Before reading on: do you think following the Law of Demeter always makes code simpler or can it sometimes add extra code? Commit to your answer.
Concept: Following the Law of Demeter reduces coupling but can sometimes add extra methods or wrappers.
By limiting access, you hide internal structure, making modules easier to change. However, you might write more small forwarding methods. This tradeoff is usually worth it for long-term code health.
Result
You understand the balance between strict rules and practical coding.
Recognizing tradeoffs helps you apply the Law of Demeter wisely, not blindly.
6
ExpertLaw of Demeter in Large Systems and Frameworks
🤔Before reading on: do you think large frameworks always strictly follow the Law of Demeter? Commit to yes or no.
Concept: In large systems, strict adherence to the Law of Demeter can be challenging and sometimes relaxed for performance or convenience.
Frameworks often provide APIs that expose internal objects, tempting developers to chain calls. Experts design APIs to balance ease of use and encapsulation, sometimes using patterns like Facade to hide complexity.
Result
You see how the Law of Demeter guides but does not rigidly control real-world design.
Understanding practical limits of the Law of Demeter prepares you for real software development challenges.
Under the Hood
The Law of Demeter works by limiting the number of direct connections a module has. Internally, this reduces the dependency graph's complexity, making changes localized. When a module only knows its immediate neighbors, the system's structure becomes more modular and less fragile.
Why designed this way?
It was created to combat the problem of tightly coupled code that is hard to maintain and extend. Early software systems suffered from 'spaghetti code' where changes caused widespread breakage. The Law of Demeter was designed to encourage encapsulation and reduce ripple effects.
┌─────────────┐
│   Module A  │
├─────────────┤
│ Calls only: │
│ - Itself   │
│ - Params   │
│ - Created  │
│ - Components│
└─────┬───────┘
      │
┌─────▼───────┐
│   Module B  │
└─────────────┘

No calls to Module C inside B from A directly.
Myth Busters - 4 Common Misconceptions
Quick: Does the Law of Demeter forbid any method chaining at all? Commit to yes or no.
Common Belief:Many think the Law of Demeter bans all method chaining.
Tap to reveal reality
Reality:It forbids chaining that reaches beyond immediate friends, but chaining within a module or its direct components is allowed.
Why it matters:Misunderstanding this can lead to overcomplicated code with unnecessary wrappers or avoiding useful patterns.
Quick: Do you think following the Law of Demeter always reduces code size? Commit to yes or no.
Common Belief:People often believe it always makes code shorter and simpler.
Tap to reveal reality
Reality:It can increase code size by adding forwarding methods, but this tradeoff improves modularity and maintainability.
Why it matters:Expecting smaller code can cause frustration or rejection of the principle when extra code appears.
Quick: Does the Law of Demeter mean modules should never access data from other modules? Commit to yes or no.
Common Belief:Some think modules should be completely isolated with no data access.
Tap to reveal reality
Reality:Modules can access data from immediate friends; the rule is about limiting indirect access, not forbidding communication.
Why it matters:Misunderstanding this can lead to overly fragmented code that is hard to integrate.
Quick: Do you think large frameworks strictly follow the Law of Demeter everywhere? Commit to yes or no.
Common Belief:Many believe all professional code strictly follows the Law of Demeter.
Tap to reveal reality
Reality:In practice, frameworks sometimes relax the rule for performance or usability reasons.
Why it matters:Believing in strict adherence can cause confusion when encountering real-world code that breaks the rule intentionally.
Expert Zone
1
The Law of Demeter encourages encapsulation but can conflict with performance optimizations that require exposing internal details.
2
Designing APIs with the Law of Demeter in mind often leads to Facade patterns that simplify complex subsystems.
3
Excessive forwarding methods to obey the Law of Demeter can clutter code; balancing clarity and strictness is a subtle art.
When NOT to use
Avoid strict Law of Demeter enforcement in performance-critical code where direct access reduces overhead. Also, in simple scripts or prototypes, the overhead of extra methods may not be justified. Alternatives include using well-documented APIs or controlled exceptions to the rule.
Production Patterns
In production, developers use the Law of Demeter to design clean APIs and modular services. Facade and Adapter patterns help hide complexity. Code reviews often check for violations to prevent tight coupling. However, pragmatic exceptions are made when justified.
Connections
Encapsulation
The Law of Demeter builds on encapsulation by enforcing limited knowledge of internal details.
Understanding encapsulation helps grasp why limiting access to immediate friends protects module internals.
Facade Design Pattern
Facade provides a simplified interface to complex subsystems, supporting the Law of Demeter.
Knowing Facade helps you design modules that obey the Law of Demeter by hiding deep object structures.
Social Networks
Both involve limiting communication to direct connections to reduce complexity and maintain privacy.
Seeing how people interact mostly with direct friends helps understand why software modules should do the same.
Common Pitfalls
#1Calling methods on objects returned by other methods (deep chaining).
Wrong approach:user.getProfile().getAddress().getZipCode();
Correct approach:user.getProfile().getZipCode(); // Profile provides direct access to zip code
Root cause:Misunderstanding that accessing nested objects breaks the Law of Demeter.
#2Adding too many forwarding methods blindly to obey the Law of Demeter.
Wrong approach:class A { getB() { return b; } } // exposing B directly
Correct approach:class A { doAction() { b.doAction(); } } // hides B inside A
Root cause:Confusing exposing internal objects with following the Law of Demeter.
#3Believing the Law of Demeter forbids all communication between modules.
Wrong approach:Avoid calling any methods on other modules, even immediate friends.
Correct approach:Call methods on immediate friends only, not on their returned objects.
Root cause:Misinterpreting the rule as isolation rather than limited knowledge.
Key Takeaways
The Law of Demeter limits a module's knowledge to its immediate connections to reduce coupling.
Following this law improves code maintainability by preventing deep chains of dependencies.
It encourages encapsulation and modular design but requires balancing strictness with practicality.
Understanding when and how to apply it helps write cleaner, more robust software.
Real-world systems use this law as a guideline, adapting it to fit performance and usability needs.

Practice

(1/5)
1.

What is the main idea behind the Law of Demeter in system design?

easy
A. An object should only communicate with its immediate friends.
B. An object can access any part of the system freely.
C. Objects should share all their internal details with others.
D. Objects must avoid any communication with other objects.

Solution

  1. Step 1: Understand the Law of Demeter principle

    The Law of Demeter states that an object should only talk to its immediate friends, meaning it should not reach deep into other objects.
  2. Step 2: Match the principle to the options

    An object should only communicate with its immediate friends. correctly describes this idea, while others contradict it.
  3. Final Answer:

    An object should only communicate with its immediate friends. -> Option A
  4. Quick Check:

    Law of Demeter = Talk only to immediate friends [OK]
Hint: Remember: Only talk to your immediate friends [OK]
Common Mistakes:
  • Thinking objects can access any part of the system
  • Believing objects should share all internal details
  • Assuming no communication is allowed between objects
2.

Which of the following code snippets follows the Law of Demeter?

class Car {
  Engine engine;
  void start() {
    engine.start();
  }
}
easy
A. Calling engine.start() directly inside Car is allowed.
B. Accessing engine.fuel.tank.level inside Car is allowed.
C. Calling engine.getFuel().getTank().getLevel() is preferred.
D. Car should access engine.fuel.tank.level directly.

Solution

  1. Step 1: Identify allowed communication

    According to the Law of Demeter, Car can call methods on its direct member engine.
  2. Step 2: Analyze the options

    Calling engine.start() directly inside Car is allowed. shows Car calling engine.start(), which is allowed. Options A, B, and C involve accessing deeper nested objects, which breaks the law.
  3. Final Answer:

    Calling engine.start() directly inside Car is allowed. -> Option A
  4. Quick Check:

    Direct member calls = Allowed [OK]
Hint: Only call methods on your direct members [OK]
Common Mistakes:
  • Accessing nested objects directly
  • Chaining multiple getters in one call
  • Ignoring encapsulation principles
3.

Consider this code snippet:

class A {
  B b;
  void doSomething() {
    int x = b.getC().getValue();
    System.out.println(x);
  }
}

Which statement about this code is true regarding the Law of Demeter?

medium
A. It follows the Law of Demeter perfectly.
B. It violates the Law of Demeter by chaining calls.
C. It violates the Law of Demeter by not calling b directly.
D. It follows the Law of Demeter by accessing getValue().

Solution

  1. Step 1: Analyze the method call chain

    The code calls b.getC().getValue(), which chains two calls to reach a nested object.
  2. Step 2: Compare with Law of Demeter

    The Law of Demeter discourages chaining calls like this; an object should only call methods on its direct members.
  3. Final Answer:

    It violates the Law of Demeter by chaining calls. -> Option B
  4. Quick Check:

    Chained calls = Violation [OK]
Hint: Watch out for chained method calls [OK]
Common Mistakes:
  • Thinking chained calls are allowed
  • Confusing direct member calls with nested calls
  • Ignoring encapsulation rules
4.

Identify the problem in this code snippet related to the Law of Demeter and suggest a fix:

class Order {
  Customer customer;
  void printCustomerCity() {
    System.out.println(customer.getAddress().getCity());
  }
}
medium
A. No problem; code follows the Law of Demeter.
B. Violation: Order should print city without any method calls.
C. Violation: Order should access Address directly. Fix by removing Customer.
D. Violation: Order accesses nested Address. Fix by adding getCity() in Customer.

Solution

  1. Step 1: Identify Law of Demeter violation

    Order calls customer.getAddress().getCity(), chaining calls to nested objects.
  2. Step 2: Suggest fix to follow Law of Demeter

    Add a getCity() method in Customer that returns the city, so Order calls only customer.getCity().
  3. Final Answer:

    Violation: Order accesses nested Address. Fix by adding getCity() in Customer. -> Option D
  4. Quick Check:

    Use direct member methods to avoid chaining [OK]
Hint: Add helper methods to avoid deep calls [OK]
Common Mistakes:
  • Ignoring nested call chains
  • Removing needed objects instead of fixing access
  • Trying to print without method calls
5.

You are designing a messaging system where ChatRoom has User objects, and each User has a Profile. To follow the Law of Demeter, how should ChatRoom get a user's display name?

hard
A. Make Profile public and access displayName directly.
B. chatRoom.getUser().getProfile().getDisplayName() chaining calls is fine.
C. Add a method getDisplayName() in User and call chatRoom.getUser().getDisplayName().
D. Let ChatRoom access Profile objects directly.

Solution

  1. Step 1: Identify Law of Demeter violation in chaining

    Chaining calls like getUser().getProfile().getDisplayName() breaks the Law of Demeter.
  2. Step 2: Apply Law of Demeter by adding helper method

    Adding getDisplayName() in User lets ChatRoom call only one method on its direct friend User.
  3. Final Answer:

    Add a method getDisplayName() in User and call chatRoom.getUser().getDisplayName(). -> Option C
  4. Quick Check:

    Use helper methods to avoid deep chains [OK]
Hint: Use helper methods in immediate objects [OK]
Common Mistakes:
  • Allowing chained calls
  • Making internal objects public
  • Accessing nested objects directly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard