Member-only story

Basic Programming Principles: The Law of Demeter, Composition over Inheritance

Eugen Hoble
4 min readJan 28, 2024

--

The Law of Demeter, often called the “Principle of Least Knowledge,” is a design guideline in object-oriented programming that encourages developers to minimize the coupling between classes or objects.

The principle can be summarized as follows: “Each unit should have limited knowledge about other units; it should only talk to its immediate friends.

In Java, you can apply the Law of Demeter by following these guidelines:

Limit Method Calls: Avoid excessive chaining of method calls, especially when navigating multiple objects. Instead, try to minimize the number of method calls by interacting with only the objects you directly need.

Not following the Law of Demeter

String result = person.getAddress().getStreet();

Following the Law of Demeter

String street = person.getStreet();

In the example above, it’s preferable to have the getStreet method directly available on the Person class rather than the chaining method calls to access the street.

Use Parameters: When a method requires information or behaviour from another object, pass that object as a parameter rather than accessing it indirectly.

--

--

No responses yet