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
参考:
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
注:在构造器中进行实际的工作,例如创建对象、有控制流等
代码坏味:
-
在构造函数中存在new操作,或者有static函数
-
构造函数中没有完全完成初始化任务(Object not fully initialized after the constructor finishes, watch out for initialize methods)
-
有控制流,例如条件语句、循环等
-
在构造函数内实现复杂的初始化动作(推荐使用factory或者builder)
-
使用初始化块(Adding or using an initialization block)
2 Digging into Collaborators
代码坏味:
-
在函数或者对象中传递对象, 却不直接使用对象,只是通过对象获取其他对象
-
函数调用链超过一次(Law of Demeter violation: method call chain walks an object grap with more than one dot[.])
-
无意义的命名:context, environment, principal, container or manager
注:对于调用第三个库的,要尽量封装为一个类或者接口(适配器模式,Adapter Mode),有Class调用接口或者适配器
3 Brittle Global State and Singletons
代码坏味:
-
使用单例
-
使用static变量或者函数
-
使用static初始化化模块
-
使用registries(Adding or using registries)
-
使用本地服务(Adding or using service locators)
4 Class Does Too Much
代码坏味:
-
Summing up what the class does includes the word and。
-
新成员无法快速阅读和理解
-
类具有仅在某些方法中使用的字段(Class has fields that are only used in some methods)
-
类具有仅对参数进行操作的静态方法(Class has static methods that only operate on parameters)