Community程式設計與開發github.com

api-design

使用「僅擴展」設計原則,設計穩定且相容的公開 API。管理 NuGet 套件與分散式系統的 API 相容性、傳輸相容性及版本控制。

api-design 是什麼?

此技能指導開發者如何設計與維護穩定、向後相容的公開 API,特別著重於 NuGet 套件與分散式系統。核心原則是「僅擴展設計」,強調絕不刪除或修改已公開的 API,僅透過新增多載、類型或選擇性功能來演化。技能詳細說明三種相容性類型:API/原始碼相容、二進位相容與傳輸相容,並提供具體的 C# 範例,區分安全變更(如新增選擇性參數)與不安全變更(如刪除或修改簽章)。此外,推薦使用 ApiApprover + Verify 進行自動化 API 表面測試,確保任何變更都經過審查。對於分散式系統,技能涵蓋傳輸格式的逐步演進策略(先支援讀取、再啟用寫入、最後設為預設),並比較各種序列化格式的傳輸相容性。最後,提供版本控制策略(語意化版本)、封裝模式與審查 PR 的清單,協助開發者避免常見的反模式,例如偽裝成修復的破壞性變更或靜默行為變更。此技能主要適用於 .NET 生態系(如 C#、Akka.NET)的開發工具(如 Visual Studio、VS Code、JetBrains Rider),但其中的原則可廣泛應用於任何語言或平台。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/csharp-api-design

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

公開 API 設計與相容性

何時使用此技能

在以下情況使用此技能:

  • 設計 NuGet 套件或程式庫的公開 API
  • 對現有公開 API 進行變更
  • 規劃分散式系統的傳輸格式變更
  • 實作版本控制策略
  • 審查包含破壞性變更的 Pull Request

三種相容性類型

類型定義範圍
API/原始碼程式碼可針對較新版本編譯公開方法簽章、類型
二進位已編譯的程式碼可針對較新版本執行組件配置、方法 Token
傳輸序列化資料可被其他版本讀取網路協定、持久化格式

破壞其中任何一種相容性都會為使用者帶來升級上的障礙。


僅擴展設計

穩定 API 的基礎:絕不刪除或修改,僅擴展。

三大支柱

  1. 既有功能不可變:一旦發行,行為與簽章即鎖定。
  2. 透過新結構提供新功能:新增多載、新型別、選擇性加入的功能。
  3. 僅在棄用期後才移除:以年為單位,而非版本。

優點

  • 舊程式碼在新版本中繼續運作
  • 新舊路徑共存
  • 升級預設為非破壞性
  • 使用者可依自己的時程升級

資源:


API 變更指南

安全變更(任何版本)

// 新增具有預設參數的多載
public void Process(Order order, CancellationToken ct = default);

// 新增現有方法的選擇性參數
public void Send(Message msg, Priority priority = Priority.Normal);

// 新增新型別、介面、列舉
public interface IOrderValidator { }
public enum OrderStatus { Pending, Complete, Cancelled }

// 新增現有類型的成員
public class Order
{
    public DateTimeOffset? ShippedAt { get; init; }  // NEW
}

不安全變更(永遠不要,或僅在主版本中)

// 刪除或重新命名公開成員
public void ProcessOrder(Order order);  // 原為:Process()

// 變更參數類型或順序
public void Process(int orderId);  // 原為:Process(Order order)

// 變更回傳類型
public Order? GetOrder(string id);  // 原為:public Order GetOrder()

// 變更存取修飾詞
internal class OrderProcessor { }  // 原為:public

// 新增無預設值的必要參數
public void Process(Order order, ILogger logger);  // 破壞呼叫者!

棄用模式

// 步驟 1:標記為過時並附上版本(任何版本)
[Obsolete("自 v1.5.0 起過時。請改用 ProcessAsync。")]
public void Process(Order order) { }

// 步驟 2:加入新的建議 API(同一個版本)
public Task ProcessAsync(Order order, CancellationToken ct = default);

// 步驟 3:在下一個主版本中移除(v2.0+)
// 僅在使用者有足夠時間遷移之後

API 核准測試

透過自動化 API 表面測試來防止意外的破壞性變更。

使用 ApiApprover + Verify

dotnet add package PublicApiGenerator
dotnet add package Verify.Xunit
[Fact]
public Task ApprovePublicApi()
{
    var api = typeof(MyLibrary.PublicClass).Assembly.GeneratePublicApi();
    return Verify(api);
}

建立 ApprovePublicApi.verified.txt:

namespace MyLibrary
{
    public class OrderProcessor
    {
        public OrderProcessor() { }
        public void Process(Order order) { }
        public Task ProcessAsync(Order order, CancellationToken ct = default) { }
    }
}

任何 API 變更都會讓測試失敗,審查者必須明確核准變更。

PR 審查流程

  1. PR 包含對 *.verified.txt 檔案的變更
  2. 審查者可在差異中看到確切的 API 表面變更
  3. 破壞性變更立即可見
  4. 需要經過審慎思考才能核准

傳輸相容性

對於分散式系統,序列化資料必須跨版本可讀。

需求

方向需求
向後相容舊寫入器 → 新讀取器(目前版本可讀取舊資料)
向前相容新寫入器 → 舊讀取器(舊版本可讀取新資料)

兩者皆需,才能實現零停機時間的滾動升級。

安全地演進傳輸格式

階段 1:加入讀取端支援(選擇性加入)

// 新型別訊息 - 先部署讀取器
public sealed record HeartbeatV2(
    Address From,
    long SequenceNr,
    long CreationTimeMs);  // 新的欄位

// 反序列化器同時處理新舊格式
public object Deserialize(byte[] data, string manifest) => manifest switch
{
    "Heartbeat" => DeserializeHeartbeatV1(data),   // 舊格式
    "HeartbeatV2" => DeserializeHeartbeatV2(data), // 新格式
    _ => throw new NotSupportedException()
};

階段 2:啟用寫入端(選擇性退出,下一個次要版本)

// 用於啟用新格式的設定(初始時預設關閉)
akka.cluster.use-heartbeat-v2 = on

階段 3:設為預設(未來版本)

在安裝基礎已吸收讀取端程式碼之後。

基於結構描述的序列化

偏好基於結構描述的格式,而非基於反射的格式:

格式類型傳輸相容性
Protocol Buffers基於結構描述絕佳 - 明確的欄位編號
MessagePack基於結構描述良好 - 配合合約
System.Text.Json基於結構描述(使用來源產生器)良好 - 明確的屬性
Newtonsoft.Json基於反射差 - 承載中包含類型名稱
BinaryFormatter基於反射極差 - 永遠不要使用

詳見 dotnet/serialization 技能。


封裝模式

內部 API

明確標記非公開 API:

// 用於文件的屬性
[InternalApi]
public class ActorSystemImpl { }

// 命名空間慣例
namespace MyLibrary.Internal
{
    public class InternalHelper { }  // 為了可擴展性而公開,非供使用者使用
}

清楚地記錄:

在 .Internal 命名空間中或標記為 [InternalApi] 的類型,可能在未通知的情況下於任何版本之間變更。

密封類別

// 應做:密封非專為繼承設計的類別
public sealed class OrderProcessor { }

// 不應做:意外地未密封
public class OrderProcessor { }  // 使用者可能繼承它,從而阻擋變更

介面隔離

// 應做:小而專注的介面
public interface IOrderReader
{
    Order? GetById(OrderId id);
}

public interface IOrderWriter
{
    Task SaveAsync(Order order);
}

// 不應做:單一巨型介面(無法新增方法而不破壞)
public interface IOrderRepository
{
    Order? GetById(OrderId id);
    Task SaveAsync(Order order);
    // 新增方法會破壞所有實作!
}

版本控制策略

語意化版本控制(實務)

版本允許的變更
修訂版 (1.0.x)錯誤修復、安全修補
次要版 (1.x.0)新功能、棄用、移除過時項目
主版號 (x.0.0)破壞性變更、移除舊 API

關鍵原則

  1. 無預警的破壞:即使是主版本也應事先公告與規劃
  2. 隨時擴展:新 API 可在任何版本中發行
  3. 先棄用再移除:[Obsolete] 至少持續一個次要版本
  4. 溝通時程:使用者需要規劃升級

Chesterton's Fence

在移除或變更某事物之前,先了解它為何存在。

假設每個公開 API 都有人在使用。如果你想變更它:

  1. 在 GitHub 上推廣此提案
  2. 記錄遷移路徑
  3. 提供棄用期間
  4. 在規劃的版本中發行

Pull Request 檢查清單

審查觸及公開 API 的 PR 時:

  • 無移除的公開成員(改用 [Obsolete])
  • 無變更的簽章(改為新增多載)
  • 無新增的必要參數(使用預設值)
  • API 核准測試已更新(已審查 .verified.txt 變更)
  • 傳輸格式變更是選擇性加入(讀取端優先)
  • 破壞性變更已記錄(發行說明、遷移指南)

反模式

偽裝成修復的破壞性變更

// "錯誤修復" 卻破壞了使用者
public async Task<Order> GetOrderAsync(OrderId id)  // 原為同步!
{
    // "修正"為非同步 - 但破壞了所有呼叫者
}

// 正確做法:新增方法,棄用舊方法
[Obsolete("請改用 GetOrderAsync")]
public Order GetOrder(OrderId id) => GetOrderAsync(id).Result;

public async Task<Order> GetOrderAsync(OrderId id) { }

靜默行為變更

// 變更預設值會破壞依賴舊行為的使用者
public void Configure(bool enableCaching = true)  // 原為 false!

// 正確做法:使用新參數名稱
public void Configure(
    bool enableCaching = false,  // 保留原始預設值
    bool enableNewCaching = true)  // 新行為為選擇性加入

多型序列化

// 避免:在傳輸格式中使用類型名稱
{ "$type": "MyApp.Order, MyApp", "Id": 123 }

// 重新命名 Order 類別 = 傳輸中斷!

// 偏好:使用明確的區別標記
{ "type": "order", "id": 123 }

資源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

相關技能