DEV Community

Dzung Nguyen
Dzung Nguyen

Posted on

1

Law of Demeter (LoD) Explained in 100 Seconds

πŸ’‘ What is Law of Demeter (LoD)?

πŸ’‘ The Law of Demeter (LoD) aimed at reducing coupling in your code. It can be summed up as:

"Only talk to your immediate friends, not to strangers."

πŸ’Ž A class or module should only use the things it directly depends on, not other objects those depend on. This keeps the code simpler, easier to test, and less connected to unnecessary details.

LoD Image


Code Example

❌ Not recommended

// Nested calls exposing internal structure
customerCity := order.GetCustomer().GetAddress().GetCity()

fmt.Printf("Customer lives in: %s\n", customerCity)
Enter fullscreen mode Exit fullscreen mode

Problem: The code relies on deeply nested calls, making it tightly coupled to the internal structure of Order, Customer, and Address.

βœ… Better

// Single method call hides internal structure
customerCity := order.GetCustomerCity() 

fmt.Printf("Customer lives in: %s\n", customerCity)
Enter fullscreen mode Exit fullscreen mode

Improvement: The GetCustomerCity() method encapsulates the internal details, exposing only the necessary functionality to the caller and reducing coupling.

🎯 Benefits of LoD

βœ… Reduced Coupling: Minimizes coupling between classes, making changes easier
βœ… Improved Readability: Code is more intuitive, focusing on high-level interactions
βœ… Hidden Implementation: Only relevant information is exposed, protecting the system from unnecessary complexity
βœ… Easier testing: Reduces the need for mocking complex nested calls

πŸ”¨ Applying LoD

βœ… Use DTOs (Data Transfer Objects) to limit the spread of data.
βœ… Apply Facade Patterns to simplify interactions with complex subsystems.
βœ… Refactor Chained Calls into single-level methods for clarity and adherence.


πŸ“° Others

Interested? πŸ˜ƒ Check out other posts from my programming principles series!


Follow me to stay updated with my future posts:

Top comments (0)

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay