kotlin-api-design

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Kotlin 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

步骤

  1. Name the domain concept, its owning type or module, and the callers that need to depend on it.
  2. Choose function ownership before adding an extension, factory, helper, or service layer.
  3. Represent a single-field domain concept with the smallest type that preserves its semantic and interop contract.
  4. Keep shared code semantic; put native SDK and platform details behind an interface or a narrowly justified expect/actual boundary.
  5. Read the focused reference for every material API decision below.
  6. 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.
  1. 明确领域概念、其所属类型或模块,以及需要依赖它的调用者。
  2. 在添加扩展函数、工厂类、辅助工具或服务层之前,确定函数的归属。
  3. 使用能保留其语义和互操作契约的最小类型来表示单字段领域概念。
  4. 保持共享代码的语义一致性;将原生SDK和平台细节封装在接口之后,或限定在合理的expect/actual边界内。
  5. 针对以下每一项重要的API决策,查阅对应的聚焦参考文档。
  6. 当公共API表面能体现领域意图、平台细节仅存在于底层、且调用者无需依赖无明确归属的便利抽象时,即完成设计。

Topic router

主题导航

SignalRead
Member vs top-level, extension, factory, service, or receiver choiceFunction ownership
Primitive obsession, one-field domain type,
@JvmInline value class
, data class, interop, or Compose stability
Value classes
Source sets, platform services, native SDKs, files, sensors, permissions, Compose Multiplatform interop, or expect/actualMultiplatform boundaries
Branching and guard-condition shapeKotlin control flow
信号查阅文档
成员函数 vs 顶层函数、扩展函数、工厂类、服务或接收者选择函数归属
原始类型滥用、单字段领域类型、
@JvmInline value class
、数据类、互操作或Compose稳定性
值类
源集、平台服务、原生SDK、文件、传感器、权限、Compose Multiplatform互操作或expect/actual多平台边界
分支和守卫条件结构Kotlin控制流

RED/GREEN agent scenarios

RED/GREEN Agent场景

  1. RED adds an extension on
    String
    to hide repository behavior. GREEN gives the behavior a domain owner or service with a meaningful dependency boundary.
  2. Novel case: shared UI needs a platform permission service. GREEN preserves a semantic shared contract and places platform SDK calls at the native leaf.
  3. Counterexample: an internal helper has one obvious owning class. GREEN keeps it a member instead of extracting a factory or value type for ceremony.
  1. RED在
    String
    上添加扩展函数以隐藏仓库行为。GREEN为该行为赋予一个领域归属类或服务,并设置有意义的依赖边界。
  2. 新场景:共享UI需要一个平台权限服务。GREEN保留语义化的共享契约,并将平台SDK调用放在原生底层。
  3. 反例:一个内部辅助工具拥有明确的所属类。GREEN将其保留为成员函数,而非为了形式化而提取为工厂类或值类型。