Welcome to our deep dive into the Law of Demeter (LoD), a software engineering principle designed to make code more modular, easier to read, and less prone to errors. Let's embark on this journey together!
The Law of Demeter, also known as the Principle of Least Knowledge, encourages you to write code that only interacts with immediate friends. It helps reduce complexity, improve readability, and minimize the ripple effect of changes.
Let's look at an example in Java, where we will violate LoD and then correct it:
Violation of Law of Demeter
class Order {
Customer customer;
Product product;
public void process() {
customer.getAddress().getCity().getName();
// ...
}
}In the above example, the Order class directly accesses the City class, violating the LoD.
Correction of Law of Demeter
class Order {
Customer customer;
Product product;
public void process() {
System.out.println(customer.getAddress().getCityName());
// ...
}
String getCityName() {
return customer.getAddress().getCity().getName();
}
}
class Address {
City city;
public City getCity() {
return city;
}
}
class City {
String name;
public String getName() {
return name;
}
}In this corrected example, the Order class now communicates with its direct friend Address and creates an intermediate method getCityName().
What is the main purpose of the Law of Demeter (LoD)?
Happy coding! 🚀