Principle of least knowledge and related design patterns

Priciple of least knowledge :

When you are designing a system, for any object be careful of the number of classes it interacts with and also how it interacts with those classes. Also known as law of Demeter(LoD).

This principle prevents us from creating designs that have a large 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 is costly to maintain and complex for others to understand.


How to implement this design priciple?

Take any object. Now from any method in that object, we should only invoke methods that belong to

1. The Object itself
2. Objects passed in as a parameter to the methods
3. Any object that method creates and instantiates.
4. Any components of objects. (Has-A relationship)

5. A global variable, accessible by O, in the scope of M

In particular, an object should avoid invoking methods of a member object returned by another method. For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot". That is, the code a.b.Method() breaks the law where a.Method() does not. As a simple example, when one wants to walk a dog, it would be folly to command the dog's legs to walk directly; instead one commands the dog and lets it take care of its own legs.(excellent explanation!)

 

Related design patterns:

Adapter pattern, facade pattern, 3-layers pattern(presentation, BLL, DAL).

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值