kotlin-api-design
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseKotlin API design
Kotlin API设计
Core principle
核心原则
Place behavior, types, and platform seams where their meaning is clearest to
callers; use the smallest public abstraction that preserves domain language and
platform independence.
将行为、类型和平台衔接层放置在对调用者而言含义最清晰的位置;使用最小的公共抽象,同时保留领域语言和平台独立性。
Procedure
步骤
- Name the domain concept, its owning type or module, and the callers that need to depend on it.
- Choose function ownership before adding an extension, factory, helper, or service layer.
- Represent a single-field domain concept with the smallest type that preserves its semantic and interop contract.
- Keep shared code semantic; put native SDK and platform details behind an interface or a narrowly justified expect/actual boundary.
- Read the focused reference for every material API decision below.
- Finish when the public surface states domain intent, platform details remain at leaves, and callers do not depend on convenience abstractions with no clear owner.
- 明确领域概念、其所属类型或模块,以及需要依赖它的调用者。
- 在添加扩展函数、工厂类、辅助工具或服务层之前,确定函数的归属。
- 使用能保留其语义和互操作契约的最小类型来表示单字段领域概念。
- 保持共享代码的语义一致性;将原生SDK和平台细节封装在接口之后,或限定在合理的expect/actual边界内。
- 针对以下每一项重要的API决策,查阅对应的聚焦参考文档。
- 当公共API表面能体现领域意图、平台细节仅存在于底层、且调用者无需依赖无明确归属的便利抽象时,即完成设计。
Topic router
主题导航
| Signal | Read |
|---|---|
| Member vs top-level, extension, factory, service, or receiver choice | Function ownership |
Primitive obsession, one-field domain type, | Value classes |
| Source sets, platform services, native SDKs, files, sensors, permissions, Compose Multiplatform interop, or expect/actual | Multiplatform boundaries |
| Branching and guard-condition shape | Kotlin control flow |
| 信号 | 查阅文档 |
|---|---|
| 成员函数 vs 顶层函数、扩展函数、工厂类、服务或接收者选择 | 函数归属 |
原始类型滥用、单字段领域类型、 | 值类 |
| 源集、平台服务、原生SDK、文件、传感器、权限、Compose Multiplatform互操作或expect/actual | 多平台边界 |
| 分支和守卫条件结构 | Kotlin控制流 |
RED/GREEN agent scenarios
RED/GREEN Agent场景
- RED adds an extension on to hide repository behavior. GREEN gives the behavior a domain owner or service with a meaningful dependency boundary.
String - Novel case: shared UI needs a platform permission service. GREEN preserves a semantic shared contract and places platform SDK calls at the native leaf.
- Counterexample: an internal helper has one obvious owning class. GREEN keeps it a member instead of extracting a factory or value type for ceremony.
- RED在上添加扩展函数以隐藏仓库行为。GREEN为该行为赋予一个领域归属类或服务,并设置有意义的依赖边界。
String - 新场景:共享UI需要一个平台权限服务。GREEN保留语义化的共享契约,并将平台SDK调用放在原生底层。
- 反例:一个内部辅助工具拥有明确的所属类。GREEN将其保留为成员函数,而非为了形式化而提取为工厂类或值类型。