Law of Demeter
Principle of least knowledge
Overview
The Law of Demeter (LoD), also known as the "Principle of Least Knowledge", states that a unit should only talk to its immediate friends and not to strangers. In other words, don't chain method calls like a.getB().getC().doSomething().
This principle helps reduce coupling between classes and makes code more maintainable.
Key Concepts
Only talk to immediate friends
Avoid method chaining (train wreck code)
Each unit should have limited knowledge
Reduces coupling between classes
Makes code more testable
Code Example
1// ❌ BAD: Violating Law of Demeter
2class OrderService {
3 public void processOrder(Order order) {
4 // Train wreck - too much knowledge about internal structure
5 String city = order.getCustomer().getAddress().getCity();
6 double discount = order.getCustomer().getMembership().getDiscount();
7 String email = order.getCustomer().getContactInfo().getEmail();
8
9 // Process with gathered info
10 }
11}
12
13// ✅ GOOD: Following Law of Demeter
14class Order {
15 private Customer customer;
16 private List<Item> items;
17
18 public String getShippingCity() {
19 return customer.getShippingCity();
20 }
21
22 public double getCustomerDiscount() {
23 return customer.getDiscount();
24 }
25
26 public String getCustomerEmail() {
27 return customer.getEmail();
28 }
29}
30
31class Customer {
32 private Address address;
33 private Membership membership;
34 private ContactInfo contactInfo;
35
36 public String getShippingCity() {
37 return address.getCity();
38 }
39
40 public double getDiscount() {
41 return membership.getDiscount();
42 }
43
44 public String getEmail() {
45 return contactInfo.getEmail();
46 }
47}
48
49class OrderService {
50 public void processOrder(Order order) {
51 // Clean - only talks to Order
52 String city = order.getShippingCity();
53 double discount = order.getCustomerDiscount();
54 String email = order.getCustomerEmail();
55
56 // Process with gathered info
57 }
58}Order exposes methods that delegate to internal objects. OrderService doesn't need to know about Address, Membership, etc.
Advantages
- ✓
Reduced coupling between classes
- ✓
Easier to change internal structures
- ✓
Better encapsulation
- ✓
More testable code
- ✓
Clearer dependencies
Best Practices
- 1.
Create wrapper methods instead of exposing internals
- 2.
Each class should only talk to: itself, parameters, objects it creates, its fields
- 3.
Use the "Tell, Don't Ask" principle
- 4.
Don't return internal mutable objects
💡 Interview Tips
Explain "train wreck" code problem
Show before/after refactoring example
Discuss how it improves maintainability
Mention it supports encapsulation