本文主要是介绍ARTS Review7 编写可测试代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原文链接:https://medium.com/feedzaitech/writing-testable-code-b3201d4538eb
这篇文章,作者主要讲了如何编写可测试的代码,一般人不愿意测试,是因为代码之间的耦合度太高,所以我们可以学习编写低耦合的代码,来方便我们开发项目。
编写可测试的代码需要遵循下面的一些原则和指导路线:
SOLID design principles
Single Responsibility Principle (SRP)
单一职责原则
Each software module should only have one reason to change
。
Open/Closed Principle (OCP)
开放关闭原则
Your classes should be open for extension but closed to modifications
Liskov Substitution Principle (LSP)
Objects of a superclass shall be replaceable with objects of its subclasses without breaking the application
Interface Segregation Principle (ISP)
接口隔离原则
No client should be forced to depend on methods it does not use.
Dependency Inversion Principle (DIP)
依赖倒置原则
High-level modules should not depend on low-level modules; both should depend on abstractions.
Abstractions should not depend on details. Details should depend upon abstractions.
Law of Demeter (LoD)
Each unit should have only limited knowledge about other units: only units “closely” related to the current unit.
Each unit should only talk to its friends; don’t talk to strangers. Only talk to your immediate friends
指导途经:
- 确保您的代码有接缝
- 不要把对象的创建与应用程序的逻辑混合在一起
- 使用依赖注入
- 不要使用全局状态
- 避免使用静态方法
- 组合优先于继承
之所以作者说有的不好测试,是因为代码的耦合度太高,牵一发而动全身,所以对于架构的设计和模块化的设计都很重要,尽量降低耦合度,这样不至于有牵一发而动全身的事情发生。
这篇关于ARTS Review7 编写可测试代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!