Problem Statement
When objects reach deeply into other objects to access data or methods, the code becomes tightly coupled and fragile. Changes in one part ripple through many others, making maintenance and testing difficult.
┌─────────┐ ┌─────────┐ ┌─────────┐ │ Client │──────▶│ ObjectA │──────▶│ ObjectB │ └─────────┘ └─────────┘ └─────────┘ Without Law of Demeter: Client calls ObjectA, then ObjectB through ObjectA (chain). With Law of Demeter: Client calls only ObjectA, which internally calls ObjectB.
The diagram shows how a client should only communicate with its direct object (ObjectA), not with ObjectB inside ObjectA, following the Law of Demeter.
### Before applying Law of Demeter (violating) ### class Engine: def start(self): print('Engine started') class Car: def __init__(self): self.engine = Engine() class Driver: def __init__(self): self.car = Car() def drive(self): # Driver reaches into car to start engine directly self.car.engine.start() ### After applying Law of Demeter (applying) ### class Engine: def start(self): print('Engine started') class Car: def __init__(self): self.engine = Engine() def start_engine(self): self.engine.start() class Driver: def __init__(self): self.car = Car() def drive(self): # Driver only talks to car, not engine directly self.car.start_engine()
What is the main idea behind the Law of Demeter in system design?
Which of the following code snippets follows the Law of Demeter?
class Car {
Engine engine;
void start() {
engine.start();
}
}Car can call methods on its direct member engine.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.engine.start() directly inside Car is allowed. -> Option AConsider 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?
b.getC().getValue(), which chains two calls to reach a nested object.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());
}
}Order calls customer.getAddress().getCity(), chaining calls to nested objects.getCity() method in Customer that returns the city, so Order calls only customer.getCity().Order accesses nested Address. Fix by adding getCity() in Customer. -> Option DYou 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?
getUser().getProfile().getDisplayName() breaks the Law of Demeter.getDisplayName() in User lets ChatRoom call only one method on its direct friend User.getDisplayName() in User and call chatRoom.getUser().getDisplayName(). -> Option CPass the test and this pattern moves unknown