Friday 31 July 2015

Principle Of Least Knowledge Principle

 Principle of least knowledge - talk only to your immediate friends.

 When you are designing a system, for any object, be careful of the number of classes it interacts with and also how it comes to interact with those classes.

This principle prevents use from creating designs that have a larger number of classes coupled together so that changes in one part of the system cascade to other parts. When you build a lot of dependencies between many classes, you are building a fragile system that will be costly to maintain and complex for others to understand.

How do we do this?
The principle tells us tat we need to make sure that we only invoke methods that belong to.

  • The object itself
  • Objects passed in as a parameter to the method
  • Any object the method creates or instantiates
  • Any components of the object.

This sounds kind of stringent doesn't it? whats the harm in calling the method of an object we get back from another call? Well, if we were to do that, then we'd be making a request of another objects sub-part (an increasing the number of object we directly know). In such cases, the principle forces use to ask the object to make the request for us; that way we don't have to know about its component object (and we keep out circle of friends small). for example:






Here's a car class that demonstrates all the ways you can call methods and still adhere to the Principle of Least Knowledge;





No comments:

Post a Comment