The Secret Law Every Developer Should Follow for Cleaner Code
There are many laws, and we should follow them. But as a developer, are you following the laws?
The Law of Demeter (LoD) is an important law that helps developers write cleaner, more maintainable code. It teaches us to limit how much an object knows about others. Instead of having deep chains of method calls, the law suggests that each object should only communicate with its immediate friends. This keeps the code easier to understand and prevents bugs.
Let’s see how we can apply the law of Demeter, and also if you are not following this law.
Without following the Law of Demeter:
class Address {
String getCity() {
return "New York";
}
}
class Customer {
Address getAddress() {
return new Address();
}
}
class Order {
Customer getCustomer() {
return new Customer();
}
}
class OrderService {
String getCustomerCity(Order order) {
return order.getCustomer().getAddress().getCity(); // Violates Law of Demeter
}
}
In this example, OrderService
has to navigate through multiple objects (Order → Customer → Address) to get the city. This creates tight coupling between classes and makes the code more fragile.
Following the Law of Demeter:
class Address {
String getCity() {
return "New York";
}
}
class Customer {
Address getAddress() {
return new Address();
}
String getCity() {
return getAddress().getCity(); // Only this class handles Address
}
}
class Order {
Customer getCustomer() {
return new Customer();
}
String getCustomerCity() {
return getCustomer().getCity(); // Only this class handles Customer
}
}
class OrderService {
String getCustomerCity(Order order) {
return order.getCustomerCity(); // Follows Law of Demeter
}
}
Now, each class only interacts with its immediate neighbor. This makes the code easier to maintain and reduces potential errors when changes are made.
Conclusion
By applying the Law of Demeter, we can reduce unnecessary dependencies and keep our code simple and organized. Following this law helps developers avoid complex method chains, making the code easier to test, modify, and understand.
Are you following the laws? 😆