What if your software could protect itself from breaking every time you change one small part?
Why Law of Demeter in LLD? - Purpose & Use Cases
Imagine you are building a complex software system where many parts need to talk to each other. Without clear rules, each part might reach deep inside other parts to get what it needs, like asking a friend to get a book from their friend's shelf instead of asking the friend directly.
This deep reaching makes the system fragile and hard to fix. If one part changes inside, many others break because they depended on those inner details. It's like if your friend moves the book to a new shelf, you have to find out and change your way of asking everywhere.
The Law of Demeter tells us to only talk to our immediate friends, not their friends. This keeps each part simple and independent. If something inside changes, only the direct friend needs to know, not everyone.
order.getCustomer().getAddress().getZipCode()
order.getCustomerZipCode()
It enables building software that is easier to maintain, less error-prone, and more flexible to change.
Think of a restaurant where the waiter asks the chef directly for the dish instead of asking the chef's assistant to ask the chef. This speeds up service and avoids confusion.
Reduces dependencies between parts of a system.
Makes code easier to change and fix.
Encourages clear and simple communication paths.
Practice
What is the main idea behind the Law of Demeter in system design?
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 AQuick Check:
Law of Demeter = Talk only to immediate friends [OK]
- Thinking objects can access any part of the system
- Believing objects should share all internal details
- Assuming no communication is allowed between objects
Which of the following code snippets follows the Law of Demeter?
class Car {
Engine engine;
void start() {
engine.start();
}
}Solution
Step 1: Identify allowed communication
According to the Law of Demeter,Carcan call methods on its direct memberengine.Step 2: Analyze the options
Callingengine.start()directly insideCaris allowed. showsCarcallingengine.start(), which is allowed. Options A, B, and C involve accessing deeper nested objects, which breaks the law.Final Answer:
Callingengine.start()directly insideCaris allowed. -> Option AQuick Check:
Direct member calls = Allowed [OK]
- Accessing nested objects directly
- Chaining multiple getters in one call
- Ignoring encapsulation principles
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?
Solution
Step 1: Analyze the method call chain
The code callsb.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 BQuick Check:
Chained calls = Violation [OK]
- Thinking chained calls are allowed
- Confusing direct member calls with nested calls
- Ignoring encapsulation rules
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());
}
}Solution
Step 1: Identify Law of Demeter violation
Ordercallscustomer.getAddress().getCity(), chaining calls to nested objects.Step 2: Suggest fix to follow Law of Demeter
Add agetCity()method inCustomerthat returns the city, soOrdercalls onlycustomer.getCity().Final Answer:
Violation:Orderaccesses nestedAddress. Fix by addinggetCity()inCustomer. -> Option DQuick Check:
Use direct member methods to avoid chaining [OK]
- Ignoring nested call chains
- Removing needed objects instead of fixing access
- Trying to print without method calls
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?
Solution
Step 1: Identify Law of Demeter violation in chaining
Chaining calls likegetUser().getProfile().getDisplayName()breaks the Law of Demeter.Step 2: Apply Law of Demeter by adding helper method
AddinggetDisplayName()inUserletsChatRoomcall only one method on its direct friendUser.Final Answer:
Add a methodgetDisplayName()inUserand callchatRoom.getUser().getDisplayName(). -> Option CQuick Check:
Use helper methods to avoid deep chains [OK]
- Allowing chained calls
- Making internal objects public
- Accessing nested objects directly
Ready to prove it?
Pass the test and this pattern moves unknown
