In this lesson, we'll explore the Law of Demeter, also known as the Principle of Least Knowledge, an important principle of object-oriented design.
We'll understand what it means, why excessive dependencies between objects create problems, how to design systems with better encapsulation and lower coupling, and how to apply this principle effectively in low-level design interviews.
Imagine you're designing a movie ticket booking system. The system allows users to browse movies, select shows, reserve seats, and book tickets.
Now, suppose we have a BookingService responsible for coordinating the booking process. When a user selects a seat, the service needs to check whether that seat is available before reserving it.
One approach is to let BookingService access the Show object, retrieve its SeatInventory, find the selected Seat, and then check its availability. If the seat is available, BookingService directly updates its reservation status.
At first, this approach might seem reasonable. But notice what's happening.
BookingService needs to know that:
Show contains a SeatInventory.SeatInventory manages Seat objects.Seat maintains its own reservation status.It depends on the internal structure of several other objects.
What happens if we change how seats are managed? Perhaps we replace the collection of Seat objects with a more efficient reservation data structure. Now, BookingService might also need to change, even though its responsibility hasn't changed.
This is the kind of unnecessary coupling that the Law of Demeter helps us avoid.
The Law of Demeter was developed during the Demeter Project at Northeastern University in the late 1980s. It's also called the Principle of Least Knowledge.
The central idea is simple: An object should have limited knowledge about other objects and interact primarily with its immediate collaborators.
This is often summarized as "Only talk to your immediate friends."
In object-oriented programming, objects collaborate by calling methods on one another. But an object shouldn't need to navigate through several other objects just to perform an operation.
Instead, it should interact with an appropriate object that exposes the required behavior. This reduces dependencies on internal implementation details and allows different parts of the system to evolve more independently.
In our booking system, the BookingService retrieves the seat inventory from the show, retrieves a particular seat, and checks whether it's available.
Now, imagine we also need to reserve that seat. BookingService might retrieve the same objects again and call a method to mark the seat as reserved.
This style of navigating through multiple objects is sometimes called a train wreck.
The problem is that BookingService becomes tightly coupled to the internal structure of Show and SeatInventory. If that structure changes, we may also need to update BookingService.
It also exposes internal details and allows BookingService to modify state that should ideally be managed by the component responsible for seat reservations.
How can we improve this design?
Instead of letting BookingService navigate through the internal objects, we can expose a meaningful operation on Show. For example, we can define a method called reserveSeats that accepts the selected seat IDs.
Now, BookingService simply calls show.reserveSeats(seatIds).
Show object can delegate the actual reservation to its SeatInventory.SeatInventory checks whether the requested seats are available and reserves them according to the system's concurrency rules.BookingService no longer needs to know how seats are stored, retrieved, or updated. It only needs to know that Show supports a seat reservation operation.
The Law of Demeter provides a useful guideline for deciding which objects a method should interact with.
In its commonly used object-oriented form, a method should generally call methods on:
These are considered its immediate collaborators.
For example, suppose BookingService has a PaymentService field. Calling a method on PaymentService follows the principle because it's a direct collaborator.
Similarly, if a method receives a Booking object as a parameter, it can call methods on that object. However, if it retrieves another object from Booking and then calls methods on that object, it starts depending on the internal structure of Booking.
The goal is to keep interactions focused on direct collaborators and avoid unnecessary dependencies on the internal details of other objects.
Following the Law of Demeter offers several benefits.
SeatInventory stores reservations, BookingService doesn't necessarily need to change.BookingService through the behavior exposed by Show rather than configuring or mocking several layers of internal objects.Overall, the principle helps us build systems where changes in one component are less likely to affect unrelated components.
Although the Law of Demeter is useful, following it too strictly can introduce unnecessary complexity.
The key is to understand whether the calling code depends on internal implementation details that should ideally remain hidden.
We should also avoid creating too many wrapper methods that simply forward calls to other objects without adding meaningful value.
For example, adding multiple methods to Booking just to expose every property of its associated Show would unnecessarily complicate the Booking interface.
Instead, introduce methods that represent meaningful behavior or expose information that the object is naturally responsible for providing.
The Law of Demeter is an important principle to keep in mind during low-level design interviews, especially when designing systems where multiple objects interact with one another.
For example, in a parking lot system, a ParkingService shouldn't need to navigate through a ParkingFloor to access a ParkingSpot and directly change its availability status.
Instead, ParkingFloor can expose methods like assignSpot() and releaseSpot() to manage its parking spots and enforce the necessary rules.
This keeps responsibilities clearly defined and reduces unnecessary dependencies between classes.
However, avoid introducing additional methods or abstractions just to follow the principle. Apply it when it genuinely improves the clarity, maintainability, or flexibility of your design.