Design: Law of Demeter Application in Software Design
Focus on the design principles and object interactions within a single module or small system. Out of scope are distributed systems, network communication, or database design.
Functional Requirements
FR1: Design a software module that follows the Law of Demeter to reduce coupling.
FR2: Ensure that objects only communicate with their immediate friends.
FR3: Avoid chaining calls that reach deep into object structures.
FR4: Demonstrate how to refactor a tightly coupled design into a loosely coupled one.
Non-Functional Requirements
NFR1: The design should minimize dependencies between modules.
NFR2: The system should be easy to maintain and extend.
NFR3: Latency and performance should not degrade significantly due to added abstraction.
NFR4: The design should be understandable by developers new to the project.
Think Before You Design
Questions to Ask
❓ Question 1
❓ Question 2
❓ Question 3
❓ Question 4
Key Components
Objects and their immediate collaborators
Interfaces or methods that expose internal structure
Encapsulation boundaries
Refactoring techniques to reduce coupling
Design Patterns
Facade pattern to hide complex subsystems
Mediator pattern to centralize communication
Tell, Don't Ask principle
Encapsulation and information hiding
Reference Architecture
Client
|
v
Module A (Facade)
|
v
Module B (Internal Objects)
- Client calls only Module A
- Module A communicates with Module B
- No direct calls from Client to Module B
- No chained calls like client.getA().getB().doSomething()
Components
Client
Any OO language
Uses the module through a simple interface without knowing internal details
Module A (Facade)
Any OO language
Provides a simplified interface and hides internal object structure
Module B (Internal Objects)
Any OO language
Contains detailed logic and data, accessed only by Module A
Request Flow
1. Client calls a method on Module A.
2. Module A performs necessary operations by calling its internal objects (Module B).
3. Module B executes logic and returns results to Module A.
4. Module A returns the final result to Client.
5. Client never calls methods on Module B directly or chains calls.
Database Schema
Not applicable as this design focuses on object interactions and coupling.
Scaling Discussion
Bottlenecks
Excessive method calls in facade can become complex.
Facade might become a god object if not carefully designed.
Performance overhead due to additional abstraction layers.
Difficulty in identifying direct collaborators if facade is too generic.
Solutions
Split facade into smaller facades for different responsibilities.
Use mediator pattern to manage complex interactions.
Profile and optimize critical paths to reduce overhead.
Maintain clear documentation of object relationships and interfaces.
Interview Tips
Time: Spend 10 minutes explaining the Law of Demeter and its importance, 15 minutes designing a simple example with a facade, and 10 minutes discussing scaling and trade-offs.
Explain how Law of Demeter reduces coupling and improves maintainability.
Show how to identify violations by spotting chained calls.
Demonstrate refactoring using facade or mediator patterns.
Discuss trade-offs between abstraction and performance.
Highlight benefits for team collaboration and code readability.
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
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.
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.
Final Answer:
An object should only communicate with its immediate friends. -> Option A
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
Step 1: Identify allowed communication
According to the Law of Demeter, Car can call methods on its direct member engine.
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.
Final Answer:
Calling engine.start() directly inside Car is allowed. -> Option A
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
Step 1: Analyze the method call chain
The code calls b.getC().getValue(), which chains two calls to reach a nested object.
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.
Final Answer:
It violates the Law of Demeter by chaining calls. -> Option B
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
Step 1: Identify Law of Demeter violation
Order calls customer.getAddress().getCity(), chaining calls to nested objects.
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().
Final Answer:
Violation: Order accesses nested Address. Fix by adding getCity() in Customer. -> Option D
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
Step 1: Identify Law of Demeter violation in chaining
Chaining calls like getUser().getProfile().getDisplayName() breaks the Law of Demeter.
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.
Final Answer:
Add a method getDisplayName() in User and call chatRoom.getUser().getDisplayName(). -> Option C
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 unknownstrongwhile earning +1 Grip toward your certificate.