Understanding the Law of Demeter: “Talk Only to Your Friends”

Law of Demeter

The Law of Demeter (LoD), also known as the Principle of Least Knowledge, is a software design guideline that promotes low coupling and high encapsulation. It encourages developers to ensure that objects only communicate with their immediate “friends” rather than accessing or depending on distant objects unnecessarily. This principle can be summarized with the phrase: “Talk only to your friends, not to strangers.” In this article, we will dive into the details of the Law of Demeter, its benefits, and practical examples to implement it effectively.

What is the Law of Demeter?

The Law of Demeter was introduced in the 1980s as a way to improve object-oriented software design. Its main goal is to reduce dependencies between different parts of the system by limiting how objects interact. According to the principle, an object should only interact with:

  • Its own methods and properties
  • Methods of its direct dependencies (parameters or injected services)
  • Methods of objects it creates or owns directly

By following this principle, developers can prevent “chain calls” or deeply nested object accesses, which can make code harder to maintain and debug.