codebase-design

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Codebase Design

Codebase Design

设计 深度模块(deep modules):一个小接口背后承载大量行为,放置在干净的 seam 处,通过该接口可测试。在设计和重构代码的任何地方,都使用这套语言和原则。目标是:对调用者而言是杠杆效应(leverage),对维护者而言是局部性(locality),对所有人而言是可测试性。
Design deep modules: A small interface behind which lies a large amount of behavior, placed at a clean seam, testable through that interface. Use this language and principles everywhere you design and refactor code. Goals: leverage for callers, locality for maintainers, testability for everyone.

词汇表

Glossary

精确使用以下术语 —— 不要替换为"组件"、"服务"、"API"或"边界"。使用一致的语言正是关键所在。
Module(模块) —— 任何具有接口和实现的东西。特意与规模无关:一个函数、类、包或跨层级切片。避免使用:单元、组件、服务。
Interface(接口) —— 调用者正确使用该模块所需知道的一切:类型签名,还包括不变性约束、顺序约束、错误模式、所需配置和性能特征。避免使用:API、签名(过于狭隘 —— 它们仅指类型层面的表面)。
Implementation(实现) —— 模块内部的内容,它的代码主体。与 Adapter(适配器) 不同:某个东西可以是一个小型适配器配大型实现(如 Postgres 仓库),也可以是一个大型适配器配小型实现(如内存中的假实现)。当讨论重点是 seam 时使用"adapter";否则使用"implementation"。
Depth(深度) —— 接口处的杠杆效应:调用者(或测试)每学习一个单位的接口就能调用的行为量。当一个模块在小型接口背后承载了大量行为时,它是 深的(deep);当接口几乎和实现一样复杂时,它是 浅的(shallow)
Seam(接缝) (Michael Feathers) —— 可以在不修改某处的情况下改变行为的位置;模块接口所在的位置。seam 放在哪里本身就是一个设计决策,与它背后放什么不同。避免使用:边界(与 DDD 的限界上下文 overloaded)。
Adapter(适配器) —— 在 seam 处满足接口的具体实现。描述的是角色(它填充什么槽位),而非实质(内部是什么)。
Leverage(杠杆效应) —— 调用者从深度中获得的好处:每学习一个单位的接口就能获得更多能力。一次实现在 N 个调用点和 M 个测试中回报。
Locality(局部性) —— 维护者从深度中获得的好处:变更、缺陷、知识和验证集中在一个地方,而不是分散在调用者之间。一次修复,处处生效。
Use the following terms precisely — do not substitute with "component", "service", "API", or "boundary". Consistent language is the point.
Module —— Anything with an interface and implementation. Intentionally agnostic to scale: a function, class, package, or cross-layer slice. Avoid: unit, component, service.
Interface —— Everything a caller needs to know to use the module correctly: type signatures, plus invariants, ordering constraints, error patterns, required configuration, and performance characteristics. Avoid: API, signature (too narrow — they only refer to the type-level surface).
Implementation —— What's inside the module, its code body. Different from Adapter: something can be a small adapter with a large implementation (like a Postgres repository), or a large adapter with a small implementation (like an in-memory fake). Use "adapter" when the focus is on seams; otherwise use "implementation".
Depth —— Leverage at the interface: the amount of behavior a caller (or test) can invoke per unit of interface learned. A module is deep when it carries a lot of behavior behind a small interface; it is shallow when the interface is almost as complex as the implementation.
Seam (Michael Feathers) —— A place where you can change behavior without modifying something; where a module's interface lives. Where to place a seam is itself a design decision, separate from what goes behind it. Avoid: boundary (overloaded with DDD's bounded context).
Adapter —— A concrete implementation that satisfies an interface at a seam. Describes a role (what slot it fills), not substance (what's inside it).
Leverage —— The benefit callers get from depth: more capability per unit of interface learned. One implementation pays off across N call sites and M tests.
Locality —— The benefit maintainers get from depth: changes, defects, knowledge, and validation are concentrated in one place instead of scattered across callers. Fix once, fix everywhere.

深 vs 浅

Deep vs Shallow

深度模块 = 小接口 + 大量实现:
┌─────────────────────┐
│   小型接口           │  ← 少量方法,简单参数
├─────────────────────┤
│                     │
│  深度实现            │  ← 隐藏的复杂逻辑
│                     │
└─────────────────────┘
浅模块 = 大接口 + 少量实现(避免):
┌─────────────────────────────────┐
│       大型接口                   │  ← 大量方法,复杂参数
├─────────────────────────────────┤
│  薄实现                         │  ← 仅透传
└─────────────────────────────────┘
设计接口时,问自己:
  • 我能减少方法数量吗?
  • 我能简化参数吗?
  • 我能在内部隐藏更多复杂性吗?
Deep module = Small interface + Large implementation:
┌─────────────────────┐
│   Small Interface   │  ← Few methods, simple parameters
├─────────────────────┤
│                     │
│  Deep Implementation│  ← Hidden complex logic
│                     │
└─────────────────────┘
Shallow module = Large interface + Thin implementation (Avoid):
┌─────────────────────────────────┐
│       Large Interface           │  ← Many methods, complex parameters
├─────────────────────────────────┤
│  Thin Implementation           │  ← Only pass-through
└─────────────────────────────────┘
When designing an interface, ask yourself:
  • Can I reduce the number of methods?
  • Can I simplify the parameters?
  • Can I hide more complexity internally?

原则

Principles

  • 深度是接口的属性,而不是实现的属性。 一个深度模块内部可以由小的、可 mock、可替换的部分组成 —— 它们只是不属于接口而已。一个模块可以有 内部 seam(对其实施私有的,由其自身测试使用)以及其接口处的 外部 seam
  • 删除测试。 想象删除这个模块。如果复杂性消失了,它就是一个透传。如果复杂性在 N 个调用者之间重新出现,那么它是有价值的。
  • 接口就是测试面。 调用者和测试穿过同一个 seam。如果你想测试越过接口,那模块的形状可能有问题。
  • 一个适配器意味着一个假设的 seam。两个适配器意味着一个真实的 seam。 除非有东西实际在 seam 处变化,否则不要引入 seam。
  • Depth is a property of the interface, not the implementation. A deep module can be composed internally of small, mockable, replaceable parts — they just don't belong to the interface. A module can have internal seams (private to its implementation, used by its own tests) as well as an external seam at its interface.
  • Delete the test. Imagine deleting this module. If complexity disappears, it's a pass-through. If complexity re-emerges across N callers, it's valuable.
  • The interface is the test surface. Callers and tests go through the same seam. If you want to test across the interface, the module's shape is probably wrong.
  • One adapter implies a hypothetical seam. Two adapters imply a real seam. Don't introduce a seam unless something actually varies at it.

设计可测试性

Designing for Testability

好的接口让测试变得自然:
  1. 接受依赖,不要创建依赖。
    typescript
    // 可测试
    function processOrder(order, paymentGateway) {}
    
    // 难以测试
    function processOrder(order) {
      const gateway = new StripeGateway();
    }
  2. 返回结果,不要产生副作用。
    typescript
    // 可测试
    function calculateDiscount(cart): Discount {}
    
    // 难以测试
    function applyDiscount(cart): void {
      cart.total -= discount;
    }
  3. 小表面积。 方法越少 = 需要的测试越少。参数越少 = 测试设置越简单。
Good interfaces make testing natural:
  1. Accept dependencies, don't create them.
    typescript
    // Testable
    function processOrder(order, paymentGateway) {}
    
    // Hard to test
    function processOrder(order) {
      const gateway = new StripeGateway();
    }
  2. Return results, don't produce side effects.
    typescript
    // Testable
    function calculateDiscount(cart): Discount {}
    
    // Hard to test
    function applyDiscount(cart): void {
      cart.total -= discount;
    }
  3. Small surface area. Fewer methods = fewer tests needed. Fewer parameters = simpler test setup.

关系

Relationships

  • Module 有且只有一个 Interface(它呈现给调用者和测试的表面)。
  • DepthModule 的一个属性,相对于其 Interface 衡量。
  • SeamModuleInterface 所在的位置。
  • Adapter 位于 Seam 处,满足 Interface
  • Depth 为调用者产生 Leverage,为维护者产生 Locality
  • A Module has exactly one Interface (the surface it presents to callers and tests).
  • Depth is a property of a Module, measured relative to its Interface.
  • A Seam is where a Module's Interface lives.
  • An Adapter sits at a Seam and satisfies an Interface.
  • Depth produces Leverage for callers and Locality for maintainers.

被否定的框架

Rejected Frameworks

  • 深度作为实现行数与接口行数的比率(Ousterhout):奖励填充实现。我们使用深度即杠杆效应(depth-as-leverage)来代替。
  • "Interface" 作为 TypeScript 的
    interface
    关键字或类的 public 方法
    :过于狭隘 —— 这里的 interface 包含调用者必须知道的每一个事实。
  • "Boundary":与 DDD 的限界上下文 overloaded。请说 seaminterface
  • Depth as ratio of implementation lines to interface lines (Ousterhout): Rewards bloated implementations. We use depth-as-leverage instead.
  • "Interface" as TypeScript's
    interface
    keyword or a class's public methods
    : Too narrow — here, interface includes every fact a caller must know.
  • "Boundary": Overloaded with DDD's bounded context. Say seam or interface instead.

深入阅读

Further Reading

  • 给定依赖关系深化一个集群 —— 见 DEEPENING.md:依赖分类、seam 纪律和替换而非分层测试。
  • 探索备选接口 —— 见 DESIGN-IT-TWICE.md:启动并行的子 agent 以多种截然不同的方式设计接口,然后在深度、局部性和 seam 放置方面进行比较。
  • Deepen a cluster given dependencies — see DEEPENING.md: Dependency classification, seam discipline, and substitution instead of layered testing.
  • Explore alternative interfaces — see DESIGN-IT-TWICE.md: Spin up parallel sub-agents to design interfaces in multiple distinct ways, then compare on depth, locality, and seam placement.