写出能用的代码很简单,写出好用的代码很难。
好用的代码,也都会遵循一此原则,这就是设计原则,它们分别是:
- 单一职责原则 (SRP)
- 开闭原则 (OCP)
- 里氏替换原则 (LSP)
- 接口隔离原则 (ISP)
- 依赖倒置原则 (DIP)
提取这五种原则的首字母缩写词,就是 SOLID 原则。下面分别进行介绍,并展示如何在 Python 中应用。
1、单一职责原则 SRP
单一职责原则(Single Responsibility Principle)这个原则的英文描述是这样的:A class or module should have a single responsibility。如果我们把它翻译成中文,那就是:一个类或者模块只负责完成一个职责(或者功能)。
让我们举一个更简单的例子,我们有一个数字 L = [n1, n2, …, nx] 的列表,我们计算一些数学函数。例如,计算最大值、平均值等。
一个不好的方法是让一个函数来完成所有的工作:
import numpy as np def math_operations(list_): # Compute Average print(f"the mean is {np.mean(list_)}") # Compute Max print(f"the max is {np.max(list_)}") math_operations(list_ = [1,2,3,4,5]) # the mean is 3.0 # the max is 5
实际开发中,你可以认为 math_operations 很庞大,揉杂了各种功能代码。
为了使这个更符合单一职责原则,我们应该做的第一件事是将函数 math_operations 拆分为更细粒度的函数,一个函数只干一件事:
def get_mean(list_): '''Compute Max''' print(f"the mean is {np.mean(list_)}") def get_max(list_): '''Compute Max''' print(f"the max is {np.max(list_)}") def main(list_): # Compute Average get_mean(list_) # Compute Max get_max(list_) main([1,2,3,4,5]) # the mean is 3.0 # the max is 5
这样做的好处就是:
- 易读易调试,更容易定位错误。
- 可复用,代码的任何部分都可以在代码的其他部分中重用。
- 可测试,为代码的每个功能创建测试更容易。
但是要增加新功能,比如计算中位数,main 函数还是很难维护,因此还需要第二个原则:OCP。
2、开闭原则 OCP
开闭原则(Open Closed Principle)就是对扩展开放,对修改关闭,这可以大大提升代码的可维护性,也来2源gaodaima#com搞(代@码&网就是说要增加新功能时只需要添加新的代码,不修改原有的代码,这样做即简单,也不会影响之前的单元测试,不容易出错,即使出错也只需要检查新添加的代码。
上述代码,可以通过将我们编写的所有函数变成一个类的子类来解决这个问题。代码如下:
import numpy as np from abc import ABC, abstractmethod class Operations(ABC): '''Operations''' @abstractmethod def operation(): pass class Mean(Operations): '''Compute Max''' def operation(list_): print(f"The mean is {np.mean(list_)}") class Max(Operations): '''Compute Max''' def operation(list_): print(f"The max is {np.max(list_)}") class Main: '''Main''' def get_operations(list_): # __subclasses__ will found all classes inheriting from Operations for operation in Operations.__subclasses__(): operation.operation(list_) if __name__ == "__main__": Main.get_operations([1,2,3,4,5]) # The mean is 3.0 # The max is 5