All About The Principle of Least Knowledge

The Principle of Least knowledge also called the law of Demeter, as explained in Eric Feminella’s blog “Principle of Least Knowledge”, is a design principle that provides guidelines for designing a system with minimal dependencies.  It is summarized in short as “Only talk to your immediate friends.”

A client should have knowledge of an object’s member, and not have access to properties and methods of other objects via the members.

The example shown in the blog has three classes: ClassA, ClassB, and ClassC. ClassA has an instance member of type ClassB and ClassB has an instance member of type ClassC. This shows that all the classes are connected one by one, and this can be extended further ClassC if need be. Now believe it or not this example violates The Principle of Least Knowledge because it creates multiple dependencies, thus reducing the maintainability because if ClassA needs some work so would all the instances of ClassA. This creates like a domino effect and keeping up with the client could pose some trouble.

Now, like the blog explains, in software development there might be some trade-offs. If the program runs better optimally with the above method, then maintenance might need to be pushed aside for just that. But it’s an important goal for the software developer to minimize dependencies, and by following guidelines provided by The Principle of Least Knowledge this becomes much easier to accomplish.

The Principle of Least knowledge is very important when it comes to coding because when it comes to programming a client itself, it becomes very easy to callback other dependencies to make things easier. But this creates more classes that, in a before blog would be referred to as “master classes” and more redundant code is created, and other dependencies are brought into the mix.

In code it seems like it’s better off if some classes don’t know the inner working of their other class, I’ve seen many programs break entirely because of one class. These classes are dependent of other classes. When one class falls all the other classes fall with it. So, It’s important to implement these dependencies so that they can be changed easily. And it’s also remembered to implement in such a way that they don’t require these chains of dependencies involved. All in all, it’s best to create a program that easy to modify and refactor so that the code is easy to work with in future development.

Link to Blog: http://www.ericfeminella.com/blog/2008/02/02/principle-of-least-knowledge/

Leave a comment

Design a site like this with WordPress.com
Get started