Law of Demeter in programming
Law of Demeter in programming You could in short paraphrase as “Don’t talk to strangers!” or “Keep Your hands in your pockets”. A class needing data from a deep chain of objects like – user.getAddress().getStreet().getNumber().
It is visible very often in OOP, less in functional approachess ! The Law of Demeter states that method only knows its closest dependencies: itself, passed parameters, created objects, and own fields. Should not be used with dot chains ( they were so fancy when we started Java 8 back in the day).

What to Remember?
- Only close neighbours: Direct descendants, do not dig through the whole value object or other domain model.
- What does it solve ? It cuts dependencies – you can change internal structure and the calling code stays the same. That means fewer bugs and easier testing and refactoring in real projects.
- Beginner trap: Follow the rule You want to tell the object what to do so it performs the operation for You instead of just retrieving the dat.
Where Law of Demeter comes from ? Why Demeter ?
The Law of Demeter in progamming takes its name from the Demeter Project at Northeastern University. Demeter, the Greek goddess of agriculture symbolized a “bottom-up” methodology to building software. Law promotes limiting knowledge of one part of the program has about others. Emphasizes louse coupling liniting the interactions between models, rather is using other actors.
The principle of minimal knowledge sharing between software components.

Law of demeter examples
BAD (train wreck – violates Law of Demeter):
const city = user.getAddress().getCity();
GOOD (with wrapper method):
const user = {
address: {
getCity: () => ‘Boston’
},
getCity() {
return this.address.getCity();
}
};
const city = user.getCity();
The law requires us to hide internal structure of any object, we just use the interface, contract in a single place to access proper data or delegate proper side effects.
Summary, tl;dr
During refactoring look for long dot chain methods and think if you can encapsulate all that logic. Often ,a small method exposing the intent instead of structure, can do the trick. The after effect might be a smaller, more focused classes with cleaner domain models.
Quoting “Kelly`s Hearoes” do not go and talk to “any friends-of-friends” I want a tight little class.
Bibliography
- Law of Demeter – Wikipedia: https://en.wikipedia.org/wiki/Law_of_Demeterwikipedia
- Law of Demeter in Java – Baeldung: https://www.baeldung.com/java-demeter-lawbaeldung


