This skill provides guidance on software design principles, emphasizing simplicity, maintainability, and clean architecture.
本技能提供软件设计原则相关指导,强调简洁性、可维护性与清晰架构。
The Four Rules of Simple Design
简单设计四原则
These rules, in priority order, guide all design decisions:
Passes the tests — The code must work correctly
Reveals intention — The code clearly expresses what it does
No duplication — Every piece of knowledge has a single representation (DRY)
Fewest elements — No unnecessary classes, methods, or code
Rules 2 and 3 are closely related and reinforce each other. When they appear to conflict, favor revealing intention — clarity for the reader takes precedence.
The rules are applied in order: never sacrifice correctness for clarity, never sacrifice clarity for DRY, and never add elements just to reduce duplication.
A module should have one, and only one, reason to change.
This means a module should be responsible to one, and only one, actor or stakeholder. When multiple actors depend on the same module, changes for one actor risk breaking functionality for another.
Software entities should be open for extension but closed for modification.
Design modules so new functionality can be added without changing existing code.
软件实体应对扩展开放,对修改关闭。
设计模块时,应确保无需修改现有代码即可添加新功能。
Liskov Substitution Principle (LSP)
里氏替换原则(LSP)
Subtypes must be substitutable for their base types.
Any code that works with a base type should work correctly with any subtype.
子类型必须能够替换其基类型。
任何适用于基类型的代码都应能正确处理其子类型。
Interface Segregation Principle (ISP)
接口隔离原则(ISP)
Clients should not be forced to depend on interfaces they do not use.
Prefer many small, specific interfaces over one large, general interface.
客户端不应被迫依赖它们不需要的接口。
优先选择多个小型、专用的接口,而非一个大型、通用的接口。
Dependency Inversion Principle (DIP)
依赖倒置原则(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 on abstractions.
高层模块不应依赖低层模块,两者都应依赖抽象。
抽象不应依赖细节,细节应依赖抽象。
Coupling and Cohesion
耦合与内聚
Maximize cohesion, minimize coupling.
最大化内聚,最小化耦合。
Cohesion
内聚
Cohesion measures how strongly related the responsibilities of a module are. High cohesion means a module does one thing well.
Signs of low cohesion:
Methods that don't use most of the class's instance variables
Unrelated methods grouped in the same class
Difficulty naming the class without using "and" or "or"
内聚衡量模块内各职责之间的关联程度。高内聚意味着模块能很好地完成单一任务。
低内聚的迹象:
方法未使用类的大部分实例变量
不相关的方法被归到同一个类中
难以给类命名,除非使用“and”或“or”
Coupling
耦合
Coupling measures the degree of interdependence between modules. Low coupling means modules can change independently.
耦合衡量模块之间的相互依赖程度。低耦合意味着模块可以独立变更。
Connascence
共生性(Connascence)
Connascence provides a framework for understanding and measuring coupling. Two components are connascent if a change to one requires a change to the other.