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()