The Law of Demeter (LoD): Keep Your Code Loosely Coupled
The Law of Demeter (LoD) is a design guideline aimed at reducing coupling in your code. Its core principle is simple: "Only talk to your immediate friends, not to strangers."
In essence, a class or module should only interact directly with objects it depends on, avoiding interactions with objects those objects depend on. This promotes simpler, more testable, and less interconnected code.
Anti-Pattern (Avoid):
<code>// Tight coupling through nested calls customerCity := order.GetCustomer().GetAddress().GetCity() fmt.Printf("Customer lives in: %s\n", customerCity)</code>
This example demonstrates tight coupling. Changes to the Order
, Customer
, or Address
classes could break this code.
Improved Approach:
<code>// Decoupled using a single method call customerCity := order.GetCustomerCity() fmt.Printf("Customer lives in: %s\n", customerCity)</code>
The GetCustomerCity()
method encapsulates the complexity, hiding the internal structure and reducing dependencies.
Benefits of LoD:
Applying LoD in Practice:
Further Exploration:
Interested in learning more about software design principles? Explore these related concepts:
Connect with me on LinkedIn, GitHub, and Twitter/X for updates on future posts.
The above is the detailed content of Law of Demeter (LoD) Explained in Seconds. For more information, please follow other related articles on the PHP Chinese website!