Design Principle - Simple Responsibility Principle

Definition

In short, classes should have a single responsibility and thus only a single reason to change.

不要存在多於一個導致類變更的原因,一個類、接口、方法只負責一項職責

The single responsibility principle (SRP) states that every class or module in a program should have responsibility for just a single piece of that program’s functionality. Further, the elements of that responsibility should be encapsulated by the responsible class rather than spread out in unrelated classes.

單一功能原則規定每個類都應該有一個單一的功能,並且該功能應該由這個類完全封裝起來。所有它的服務都應該嚴密的和該功能平行。

Advantage

  • 降低類的複雜度。
  • 提高了代碼的可讀性。
  • 提高了系統的可維護性。
  • 降低了變更引起的風險。

Code Example

Now we have an interface called ICourse that it can retrive course name, course video, study course and refund.
在這裏插入圖片描述

Usually, we implement that interface like this. The implementation like this has more than one responsibilities.
在這裏插入圖片描述

How do we improve that representation ?
Think for a moment, getCourseName and getCourseVideo both belong to represent course info. We can use ICourseInfo interface to replace those. Then studyCourse and refundCourse both belong to manage course. Therefore, we can use ICourseManage interface to do that.

在這裏插入圖片描述
在這裏插入圖片描述

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章