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.
Design Principle - Simple Responsibility Principle

Usually, we implement that interface like this. The implementation like this has more than one responsibilities.
Design Principle - Simple Responsibility Principle

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.

Design Principle - Simple Responsibility Principle
Design Principle - Simple Responsibility Principle

Design Principle - Simple Responsibility Principle