编写可测代码

Interface

The bigger the interface, the weaker the abstraction

  • Name Your Interfaces Arguments

  • Keep Interfaces Samll

  • Accpt Interfaces, Return Concrete Types

  • Use Existing Interfaces

  • Don't Force Interfaces

Writing Testable Code

  • Dependency Injecton(依赖注入)

  • Single Responsibility Principle(SRP,单一职责)

  • Adapter Pattarn

参考:

Guide: Writing Testable Code

Flaw: Constructor does Real Work

Flow

  • Constructor does Real Work(构造器干真实的活)

  • Digging into Collaborators()

  • Brittle Global State and Singletons(全局状态和单例)

  • Class Does Too Much(类做太多的事情)

1 Constructor does Real Work

注:在构造器中进行实际的工作,例如创建对象、有控制流等

代码坏味:

  1. 在构造函数中存在new操作,或者有static函数

  2. 构造函数中没有完全完成初始化任务(Object not fully initialized after the constructor finishes, watch out for initialize methods)

  3. 有控制流,例如条件语句、循环等

  4. 在构造函数内实现复杂的初始化动作(推荐使用factory或者builder)

  5. 使用初始化块(Adding or using an initialization block)

2 Digging into Collaborators

代码坏味:

  1. 在函数或者对象中传递对象, 却不直接使用对象,只是通过对象获取其他对象

  2. 函数调用链超过一次(Law of Demeter violation: method call chain walks an object grap with more than one dot[.])

  3. 无意义的命名:context, environment, principal, container or manager

注:对于调用第三个库的,要尽量封装为一个类或者接口(适配器模式,Adapter Mode),有Class调用接口或者适配器

3 Brittle Global State and Singletons

代码坏味:

  1. 使用单例

  2. 使用static变量或者函数

  3. 使用static初始化化模块

  4. 使用registries(Adding or using registries)

  5. 使用本地服务(Adding or using service locators)

4 Class Does Too Much

代码坏味:

  1. Summing up what the class does includes the word and。

  2. 新成员无法快速阅读和理解

  3. 类具有仅在某些方法中使用的字段(Class has fields that are only used in some methods)

  4. 类具有仅对参数进行操作的静态方法(Class has static methods that only operate on parameters)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值