architecture-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseArchitecture Patterns
架构模式
Consolidated architecture validation and enforcement patterns covering clean architecture, backend layer separation, project structure conventions, and test standards. Each category has individual rule files in loaded on-demand.
references/整合了针对整洁架构、后端分层、项目结构约定及测试标准的架构验证与规范模式。每个分类在目录下都有独立的规则文件,可按需加载。
references/Quick Reference
快速参考
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| Clean Architecture | 3 | HIGH | SOLID principles, hexagonal architecture, ports & adapters, DDD |
| Project Structure | 2 | HIGH | Folder conventions, nesting depth, import direction, barrel files |
| Backend Layers | 3 | HIGH | Router/service/repository separation, DI, file naming |
| Test Standards | 3 | MEDIUM | AAA pattern, naming conventions, coverage thresholds |
| Right-Sizing | 2 | HIGH | Architecture tier selection, over-engineering prevention, context-aware enforcement |
Total: 13 rules across 5 categories
Quick Start
快速开始
python
undefinedpython
undefinedClean Architecture: Dependency Inversion via Protocol
Clean Architecture: Dependency Inversion via Protocol
class IUserRepository(Protocol):
async def get_by_id(self, id: str) -> User | None: ...
class UserService:
def init(self, repo: IUserRepository):
self._repo = repo # Depends on abstraction, not concretion
class IUserRepository(Protocol):
async def get_by_id(self, id: str) -> User | None: ...
class UserService:
def init(self, repo: IUserRepository):
self._repo = repo # Depends on abstraction, not concretion
FastAPI DI chain: DB -> Repository -> Service
FastAPI DI chain: DB -> Repository -> Service
def get_user_service(db: AsyncSession = Depends(get_db)) -> UserService:
return UserService(PostgresUserRepository(db))
undefineddef get_user_service(db: AsyncSession = Depends(get_db)) -> UserService:
return UserService(PostgresUserRepository(db))
undefinedProject Structure: Unidirectional Import Architecture
Project Structure: Unidirectional Import Architecture
shared/lib -> components -> features -> app
(lowest) (highest)
shared/lib -> components -> features -> app
(lowest) (highest)
Backend Layers: Strict Separation
Backend Layers: Strict Separation
Routers (HTTP) -> Services (Business Logic) -> Repositories (Data Access)
undefinedRouters (HTTP) -> Services (Business Logic) -> Repositories (Data Access)
undefinedClean Architecture
整洁架构
SOLID principles, hexagonal architecture, ports and adapters, and DDD tactical patterns for maintainable backends.
| Rule | File | Key Pattern |
|---|---|---|
| Hexagonal Architecture | | Driving/driven ports, adapter implementations, layer structure |
| SOLID & Dependency Rule | | Protocol-based interfaces, dependency inversion, FastAPI DI |
| DDD Tactical Patterns | | Entities, value objects, aggregate roots, domain events |
基于SOLID原则、六边形架构、端口与适配器以及DDD战术模式的可维护后端架构指南。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 六边形架构 | | 驱动/被驱动端口、适配器实现、分层结构 |
| SOLID与依赖规则 | | 基于Protocol的接口、依赖倒置、FastAPI依赖注入 |
| DDD战术模式 | | 实体、值对象、聚合根、领域事件 |
Key Decisions
关键决策
| Decision | Recommendation |
|---|---|
| Protocol vs ABC | Protocol (structural typing) |
| Dataclass vs Pydantic | Dataclass for domain, Pydantic for API |
| Repository granularity | One per aggregate root |
| Transaction boundary | Service layer, not repository |
| Event publishing | Collect in aggregate, publish after commit |
| 决策项 | 推荐方案 |
|---|---|
| Protocol vs ABC | Protocol(结构类型) |
| Dataclass vs Pydantic | 领域层用Dataclass,API层用Pydantic |
| 仓储粒度 | 每个聚合根对应一个仓储 |
| 事务边界 | 服务层,而非仓储层 |
| 事件发布 | 在聚合中收集,提交后发布 |
Project Structure
项目结构
Feature-based organization, max nesting depth, unidirectional imports, and barrel file prevention.
| Rule | File | Key Pattern |
|---|---|---|
| Folder Structure & Nesting | | React/Next.js and FastAPI layouts, 4-level max nesting, barrel file rules |
| Import Direction & Location | | Unidirectional imports, cross-feature prevention, component/hook placement |
基于功能的组织方式、最大嵌套深度、单向导入以及禁止桶文件的规范。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 目录结构与嵌套 | | React/Next.js和FastAPI布局、最多4层嵌套、桶文件规则 |
| 导入方向与位置 | | 单向导入、跨功能模块禁止、组件/钩子放置规则 |
Blocking Rules
阻断性规则
| Rule | Check |
|---|---|
| Max Nesting | Max 4 levels from src/ or app/ |
| No Barrel Files | No index.ts re-exports (tree-shaking issues) |
| Component Location | React components in components/ or features/ only |
| Hook Location | Custom hooks in hooks/ or features/*/hooks/ only |
| Import Direction | Unidirectional: shared -> components -> features -> app |
| 规则 | 检查项 |
|---|---|
| 最大嵌套深度 | 从src/或app/开始最多4层 |
| 禁止桶文件 | 禁止index.ts重导出(存在tree-shaking问题) |
| 组件位置 | React组件仅可放在components/或features/目录下 |
| 钩子位置 | 自定义钩子仅可放在hooks/或features/*/hooks/目录下 |
| 导入方向 | 单向导入:shared -> components -> features -> app |
Backend Layers
后端分层
FastAPI Clean Architecture with router/service/repository layer separation and blocking validation.
| Rule | File | Key Pattern |
|---|---|---|
| Layer Separation | | Router/service/repository boundaries, forbidden patterns, async rules |
| Dependency Injection | | Depends() chains, auth patterns, testing with DI overrides |
| File Naming & Exceptions | | Naming conventions, domain exceptions, violation detection |
基于FastAPI的整洁架构,包含路由/服务/仓储分层分离及强制验证。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 分层分离 | | 路由/服务/仓储边界、禁止模式、异步规则 |
| 依赖注入 | | Depends()链、认证模式、依赖注入覆盖测试 |
| 文件命名与异常 | | 命名规范、领域异常、违规检测 |
Layer Boundaries
分层边界
| Layer | Responsibility | Forbidden |
|---|---|---|
| Routers | HTTP concerns, request parsing, auth checks | Database operations, business logic |
| Services | Business logic, validation, orchestration | HTTPException, Request objects |
| Repositories | Data access, queries, persistence | HTTP concerns, business logic |
| 层级 | 职责 | 禁止操作 |
|---|---|---|
| 路由层 | HTTP相关处理、请求解析、认证检查 | 数据库操作、业务逻辑 |
| 服务层 | 业务逻辑、验证、编排 | HTTPException、Request对象 |
| 仓储层 | 数据访问、查询、持久化 | HTTP相关处理、业务逻辑 |
Test Standards
测试标准
Testing best practices with AAA pattern, naming conventions, isolation, and coverage thresholds.
| Rule | File | Key Pattern |
|---|---|---|
| AAA Pattern & Isolation | | Arrange-Act-Assert, test isolation, parameterized tests |
| Naming Conventions | | Descriptive behavior-focused names for Python and TypeScript |
| Coverage & Location | | Coverage thresholds, fixture scopes, test file placement rules |
包含AAA模式、命名规范、隔离性以及覆盖率阈值的测试最佳实践。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| AAA模式与隔离性 | | Arrange-Act-Assert、测试隔离、参数化测试 |
| 命名规范 | | Python和TypeScript的行为描述型命名 |
| 覆盖率与位置 | | 覆盖率阈值、夹具作用域、测试文件放置规则 |
Coverage Requirements
覆盖率要求
| Area | Minimum | Target |
|---|---|---|
| Overall | 80% | 90% |
| Business Logic | 90% | 100% |
| Critical Paths | 95% | 100% |
| New Code | 100% | 100% |
| 范围 | 最低要求 | 目标值 |
|---|---|---|
| 整体 | 80% | 90% |
| 业务逻辑 | 90% | 100% |
| 关键路径 | 95% | 100% |
| 新代码 | 100% | 100% |
Right-Sizing
架构规模适配
Context-aware backend architecture enforcement. Rules adjust strictness based on project tier detected by .
scope-appropriate-architectureEnforcement procedure:
- Read project tier from context (set during brainstorming/implement Step 0)
scope-appropriate-architecture - If no tier set, auto-detect using signals in
rules/right-sizing-tiers.md - Apply tier-based enforcement matrix — skip rules marked OFF for detected tier
- Security rules are tier-independent — always enforce SQL parameterization, input validation, auth checks
| Rule | File | Key Pattern |
|---|---|---|
| Architecture Sizing Tiers | | Interview/MVP/production/enterprise sizing matrix, LOC estimates, detection signals |
| Right-Sizing Decision Guide | | ORM, auth, error handling, testing recommendations per tier, over-engineering tax |
上下文感知型后端架构规范。规则会根据检测到的项目层级调整严格程度。
scope-appropriate-architecture实施流程:
- 从上下文读取项目层级(在头脑风暴/实施第0步时设置)
scope-appropriate-architecture - 若未设置层级,使用中的信号自动检测
rules/right-sizing-tiers.md - 应用基于层级的实施矩阵 — 跳过标记为OFF的规则
- 安全规则与层级无关 — 始终强制SQL参数化、输入验证、认证检查
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 架构规模层级 | | 面试/MVP/生产/企业级规模矩阵、代码行数估算、检测信号 |
| 规模适配决策指南 | | 各层级下ORM、认证、错误处理、测试的推荐方案、过度设计成本 |
Tier-Based Rule Enforcement
基于层级的规则实施
| Rule | Interview | MVP | Production | Enterprise |
|---|---|---|---|---|
| Layer separation | OFF | WARN | BLOCK | BLOCK |
| Repository pattern | OFF | OFF | WARN | BLOCK |
| Domain exceptions | OFF | OFF | BLOCK | BLOCK |
| Dependency injection | OFF | WARN | BLOCK | BLOCK |
| OpenAPI documentation | OFF | OFF | WARN | BLOCK |
Manual override: User can set tier explicitly to bypass auto-detection (e.g., "I want enterprise patterns for this take-home to demonstrate skill").
| 规则 | 面试项目 | MVP | 生产环境 | 企业级 |
|---|---|---|---|---|
| 分层分离 | 关闭 | 警告 | 阻断 | 阻断 |
| 仓储模式 | 关闭 | 关闭 | 警告 | 阻断 |
| 领域异常 | 关闭 | 关闭 | 阻断 | 阻断 |
| 依赖注入 | 关闭 | 警告 | 阻断 | 阻断 |
| OpenAPI文档 | 关闭 | 关闭 | 警告 | 阻断 |
手动覆盖: 用户可显式设置层级以绕过自动检测(例如:“我希望这个带回家的项目使用企业级模式来展示技能”)。
Decision Flowchart
决策流程图
Is this a take-home or hackathon?
YES --> Flat architecture. Single file or 3-5 files. Done.
NO -->
Is this a prototype or MVP with < 3 months runway?
YES --> Simple layered. Routes + services + models. No abstractions.
NO -->
Do you have > 5 engineers or complex domain rules?
YES --> Clean architecture with ports/adapters.
NO --> Layered architecture. Add abstractions only when pain appears.Is this a take-home or hackathon?
YES --> Flat architecture. Single file or 3-5 files. Done.
NO -->
Is this a prototype or MVP with < 3 months runway?
YES --> Simple layered. Routes + services + models. No abstractions.
NO -->
Do you have > 5 engineers or complex domain rules?
YES --> Clean architecture with ports/adapters.
NO --> Layered architecture. Add abstractions only when pain appears.Anti-Patterns (FORBIDDEN)
反模式(禁止)
python
undefinedpython
undefinedCLEAN ARCHITECTURE
CLEAN ARCHITECTURE
NEVER import infrastructure in domain layer
NEVER import infrastructure in domain layer
from app.infrastructure.database import engine # In domain layer!
from app.infrastructure.database import engine # In domain layer!
NEVER leak ORM models to API layer
NEVER leak ORM models to API layer
@router.get("/users/{id}")
async def get_user(id: str, db: Session) -> UserModel: # Returns ORM model!
@router.get("/users/{id}")
async def get_user(id: str, db: Session) -> UserModel: # Returns ORM model!
NEVER have domain depend on framework
NEVER have domain depend on framework
from fastapi import HTTPException
class UserService:
def get(self, id: str):
raise HTTPException(404) # Framework in domain!
from fastapi import HTTPException
class UserService:
def get(self, id: str):
raise HTTPException(404) # Framework in domain!
PROJECT STRUCTURE
PROJECT STRUCTURE
NEVER create files deeper than 4 levels from src/
NEVER create files deeper than 4 levels from src/
NEVER create barrel files (index.ts re-exports)
NEVER create barrel files (index.ts re-exports)
NEVER import from higher layers (features importing from app)
NEVER import from higher layers (features importing from app)
NEVER import across features (use shared/ for common code)
NEVER import across features (use shared/ for common code)
BACKEND LAYERS
BACKEND LAYERS
NEVER use database operations in routers
NEVER use database operations in routers
NEVER raise HTTPException in services
NEVER raise HTTPException in services
NEVER instantiate services without Depends()
NEVER instantiate services without Depends()
TEST STANDARDS
TEST STANDARDS
NEVER mix test files with source code
NEVER mix test files with source code
NEVER use non-descriptive test names (test1, test, works)
NEVER use non-descriptive test names (test1, test, works)
NEVER share mutable state between tests without reset
NEVER share mutable state between tests without reset
undefinedundefinedRelated Skills
相关技能
- - Project tier detection that drives right-sizing enforcement
scope-appropriate-architecture - - YAGNI gate uses tier context to validate complexity
quality-gates - - Distributed locking, resilience, idempotency patterns
distributed-systems - - REST API design, versioning, error handling
api-design - - Comprehensive testing patterns and strategies
testing-patterns - - FastAPI, SQLAlchemy, asyncio patterns
python-backend - - Schema design, query optimization, migrations
database-patterns
- - 驱动规模适配实施的项目层级检测技能
scope-appropriate-architecture - - YAGNI检查门使用层级上下文验证复杂度
quality-gates - - 分布式锁、弹性设计、幂等性模式
distributed-systems - - REST API设计、版本化、错误处理
api-design - - 全面的测试模式与策略
testing-patterns - - FastAPI、SQLAlchemy、asyncio模式
python-backend - - schema设计、查询优化、迁移
database-patterns