The Principle of Least Knowledge

The rules promoted by this principle are:

  1. Each unit should have only limited knowledge about other units: only units “closely” related to the current unit.

  2. Each unit should only talk to its friends; don’t talk to strangers.

  3. Only talk to your immediate friends.

So, the idea behind this principle means that, inside your application, the code that we write should express knowledge only of its surroundings. This guideline promotes the notion of loose coupling in your codebase, which leads to more maintainability.

With regards to object-oriented programming, a method of an object may only call methods of:

  1. The object itself.

  2. An argument of the method.

  3. Any object created within the method.

  4. Any direct properties/fields of the object

The One Dot Principle. If you find yourself using more than one dot to access a property or method, the chances are high that you are not following The Principle of Least Knowledge. You should prevent something like A.getObjectB().getObjectC().display() this sort of statement is a violation of Law of Demeter.

The Principle of Least Knowledge (Law of Demeter) gives us a guideline how to achieve loose coupling in our code and helps to properly encapsulate the knowledge of some complicated operations or logic into the places where they should be.

Last updated

Was this helpful?