π‘ 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.
Code Example
β Not recommended
// Nested calls exposing internal structure
customerCity := order.GetCustomer().GetAddress().GetCity()
fmt.Printf("Customer lives in: %s\n", customerCity)
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)
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!
- Dependency Inversion Principle (DIP) Explained in 100 Seconds
- Golang Dependency Injection - Just in 5 Minutes!
- Interface Segregation Principle (ISP) Explained in 100 Seconds
- You Arenβt Gonna Need It Principle (YAGNI) Explained in 100 Seconds
- Liskov Substitution Principle (LSP) Explained in 100 Seconds
- KISS Design Principle Explained in 100 Seconds
- DRY Principle Explained in 100 Seconds
- "Tell, Don't Ask" Principle Explained in 100 Seconds
Follow me to stay updated with my future posts:
Top comments (0)