Law of Demeter (LoD) 🎯

beginner
15 min

Law of Demeter (LoD) 🎯

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!

What is the Law of Demeter? 📝

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.

Why is the Law of Demeter important? 💡

  • Reduced Complexity: By limiting interactions, LoD makes your code simpler and easier to understand.
  • Improved Readability: The principle helps avoid tangled, spaghetti-like code structures.
  • Lower Error Rates: Fewer interactions mean fewer chances for errors and bugs.

How does the Law of Demeter work? 📝

  • Direct Communication: Only communicate with the objects you create or are passed to you as arguments.
  • Minimize Dependencies: Limit the number of objects your objects depend on.
  • Avoid Long Method Chains: Long chains increase complexity and are harder to maintain.

Applying the Law of Demeter 🎯

Let's look at an example in Java, where we will violate LoD and then correct it:

Violation of Law of Demeter

java
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

java
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().

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the main purpose of the Law of Demeter (LoD)?

Happy coding! 🚀