Law of Demeter: Only Talk to Your Friends

Code can become tangled when classes and objects reach too far, relying on details from other parts of the system. The Law of Demeter says you should only communicate with your direct friends—never distant strangers.

This principle encourages you to keep connections short and simple. When you only use what you need, your code is easier to change and less likely to break if something else changes.

Passing a note through a chain of friends
Imagine you want to pass a message to someone in a classroom. If you give the note directly to your friend, it gets there quickly and safely. If you hand it through many people, it might get lost or changed.

Real-Life Analogy: Passing Notes in Class

Think of each object as a person in a room. If you want to get something done, you should ask your friend directly—not ask your friend to ask their friend, and so on. The more people involved, the more complicated and fragile things become.

  • Direct communication is faster and safer.
  • Every extra link in the chain is a potential problem.
  • Less dependency means fewer surprises if something changes.

What the Law of Demeter Means for Code

Objects should only interact with:

  • Themselves
  • Their direct components (like their own fields or properties)
  • Objects passed as arguments
  • Objects they create themselves

Benefits of Following the Law

When your code follows this principle, you can change or update one part without affecting everything else.

  • Easier maintenance and testing
  • Lower risk of bugs spreading through the system

Common Pitfalls

It can be tempting to reach into objects' internal parts for convenience, but this quickly leads to tangled, fragile code.

  • Avoid chaining calls like: a.getB().getC().doSomething()
  • Keep each object focused on its own role

Final Thoughts

The Law of Demeter helps you keep your code clear and reliable. By only talking to your "friends", you avoid hidden dependencies and make your software much easier to manage.

Law of Demeter: Only Talk to Your Friends | SimplyAdvanced.dev