code-modularization-evaluator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Modularization Evaluator

代码模块化评估工具

Evaluate code modularization using the Balanced Coupling Model from Vlad Khononov's "Balancing Coupling in Software Design." This skill helps identify problematic coupling patterns and provides actionable refactoring guidance.
使用Vlad Khononov所著《软件设计中的耦合平衡》一书中的平衡耦合模型评估代码模块化。该工具可帮助识别有问题的耦合模式,并提供可落地的重构指导。

Core Principle

核心原则

Coupling is not inherently bad—misdesigned coupling is bad. The goal is balanced coupling, not zero coupling.
The fundamental formula:
MODULARITY = (STRENGTH XOR DISTANCE) OR NOT VOLATILITY
A system achieves modularity when:
  • High integration strength components are close together (same module/service)
  • Low integration strength components can be far apart (different services)
  • Low volatility components can tolerate coupling mismatches
耦合本身并非坏事——设计不当的耦合才是问题所在。 目标是实现平衡耦合,而非零耦合。
基础公式:
MODULARITY = (STRENGTH XOR DISTANCE) OR NOT VOLATILITY
系统实现模块化的条件:
  • 高集成强度的组件彼此靠近(同一模块/服务)
  • 低集成强度的组件可分散部署(不同服务)
  • 低易变性组件可容忍耦合不匹配

The Three Dimensions of Coupling

耦合的三个维度

Always evaluate coupling across these three dimensions:
需始终从以下三个维度评估耦合:

1. Integration Strength (What knowledge is shared?)

1. 集成强度(共享哪些知识?)

From strongest (worst) to weakest (best):
LevelTypeDescriptionExample
1IntrusiveUsing non-public interfacesDirect database access to another service, reflection on private fields
2FunctionalSharing business logic/rulesSame validation duplicated in two places, order-dependent operations
3ModelSharing domain modelsTwo services using identical entity definitions
4ContractOnly explicit interfacesWell-designed APIs, DTOs, protocols
从最强(最差)到最弱(最佳)排序:
级别类型描述示例
1侵入式(Intrusive)使用非公开接口直接访问其他服务的数据库、通过反射访问私有字段
2功能式(Functional)共享业务逻辑/规则相同验证逻辑在两处重复、依赖执行顺序的操作
3模型式(Model)共享领域模型两个服务使用完全相同的实体定义
4契约式(Contract)仅依赖显式接口设计良好的API、DTO、协议

2. Distance (How far does knowledge travel?)

2. 距离(知识传递的跨度?)

From closest to most distant:
  1. Methods within same class
  2. Classes within same file
  3. Classes in same namespace/package
  4. Modules in different namespaces
  5. Separate services/microservices
  6. Services owned by different teams
  7. Different systems/organizations
从最近到最远排序:
  1. 同一类中的方法
  2. 同一文件中的类
  3. 同一命名空间/包中的类
  4. 不同命名空间中的模块
  5. 独立服务/微服务
  6. 不同团队负责的服务
  7. 不同系统/组织

3. Volatility (How often will it change?)

3. 易变性(变更频率?)

Use Domain-Driven Design subdomain classification:
  • Core subdomains: High volatility (competitive advantage, frequent changes)
  • Supporting subdomains: Low volatility (necessary but not differentiating)
  • Generic subdomains: Low volatility (solved problems, stable)
采用领域驱动设计的子域分类:
  • 核心子域:高易变性(构成竞争优势,频繁变更)
  • 支撑子域:低易变性(必要但不具备差异化)
  • 通用子域:低易变性(已解决的通用问题,稳定)

Decision Framework

决策框架

When evaluating code, apply this matrix:
Integration StrengthDistanceResult
HighHigh❌ COMPLEXITY (Distributed monolith)
LowLow❌ COMPLEXITY (Unnecessary abstraction)
HighLow✅ MODULARITY (Related things together)
LowHigh✅ MODULARITY (Independent components apart)
Exception: If volatility is LOW, coupling mismatches are acceptable.
评估代码时,应用以下矩阵:
集成强度距离结果
❌ 复杂度(分布式单体)
❌ 复杂度(不必要的抽象)
✅ 模块化(相关组件聚合)
✅ 模块化(独立组件分散)
例外情况:若易变性为低,则耦合不匹配是可接受的。

Connascence Analysis

共生(Connascence)分析

Use connascence to identify specific coupling types. See
references/connascence-types.md
for detailed examples.
利用共生概念识别特定耦合类型。详细示例请参见
references/connascence-types.md

Static Connascence (Compile-time, easier to fix)

静态共生(编译期,易修复)

Ordered weakest to strongest:
  1. Name (CoN): Components agree on names
  2. Type (CoT): Components agree on types
  3. Meaning (CoM): Components agree on value meanings (magic numbers)
  4. Position (CoP): Components agree on order of values
  5. Algorithm (CoA): Components share algorithm logic
按从弱到强排序:
  1. 名称共生(CoN):组件使用统一的命名
  2. 类型共生(CoT):组件使用统一的类型
  3. 含义共生(CoM):组件对值的含义达成一致(如魔法值)
  4. 位置共生(CoP):组件对值的顺序达成一致
  5. 算法共生(CoA):组件共享算法逻辑

Dynamic Connascence (Runtime, harder to detect)

动态共生(运行期,难检测)

Ordered weakest to strongest: 6. Execution (CoE): Order of method calls matters 7. Timing (CoTm): Timing of execution matters 8. Value (CoV): Multiple values must change together 9. Identity (CoI): Must reference same instance
按从弱到强排序: 6. 执行共生(CoE):方法调用顺序有要求 7. 时序共生(CoTm):执行时序有要求 8. 值共生(CoV):多个值必须同步变更 9. 标识共生(CoI):必须引用同一实例

Connascence Rules

共生规则

  1. Minimize overall connascence
  2. Minimize connascence crossing module boundaries
  3. Maximize connascence within module boundaries
  4. Convert stronger connascence to weaker forms
  5. As distance increases, connascence should weaken
  1. 最小化整体共生程度
  2. 最小化跨模块边界的共生
  3. 最大化模块内部的共生
  4. 将强共生转换为弱共生形式
  5. 随着距离增加,共生程度应减弱

Evaluation Checklist

评估检查清单

When analyzing code, check for:
分析代码时,需检查以下内容:

Red Flags (Immediate Action Required)

红色预警(需立即处理)

  • Direct database access to another service's data (Intrusive coupling)
  • Reflection to access private fields
  • Business logic duplicated across services
  • Microservices requiring synchronized deployments
  • CBO (Coupling Between Objects) > 14 for a class
  • Instability index 0.3-0.7 for frequently-changing modules
  • Circular dependencies between modules
  • 直接访问其他服务的数据库(侵入式耦合)
  • 通过反射访问私有字段
  • 业务逻辑在多个服务中重复
  • 微服务需要同步部署
  • 类的CBO(对象间耦合度)>14
  • 频繁变更模块的不稳定指数在0.3-0.7之间
  • 模块间存在循环依赖

Warning Signs (Investigate Further)

警告信号(需进一步调查)

  • Magic numbers/values shared between components (CoM)
  • Position-dependent parameters in APIs (CoP)
  • Algorithm logic duplicated in multiple places (CoA)
  • Methods must be called in specific order (CoE)
  • Long method chains:
    a.b().c().d()
    (Law of Demeter violation)
  • Classes with "Manager", "Helper", "Utility" doing too much
  • 组件间共享魔法值/常量(CoM)
  • API参数依赖位置顺序(CoP)
  • 算法逻辑在多处重复(CoA)
  • 方法必须按特定顺序调用(CoE)
  • 长方法链:
    a.b().c().d()
    (违反迪米特法则)
  • 包含“Manager”“Helper”“Utility”等名称的类职责过多

Healthy Patterns

健康模式

  • Contract-based integration between services
  • DTOs that truly abstract internal models
  • High cohesion within modules
  • Single responsibility per class
  • Dependency injection for external dependencies
  • 服务间基于契约的集成
  • 真正抽象内部模型的DTO
  • 模块内高内聚
  • 类遵循单一职责原则
  • 外部依赖采用依赖注入

Refactoring Strategies

重构策略

By Integration Strength Problem

针对集成强度问题

Intrusive → Contract Coupling:
  1. Identify all direct dependencies on implementation details
  2. Define explicit interface/contract
  3. Create adapter layer
  4. Route all access through adapter
Functional → Model Coupling:
  1. Extract shared business logic to dedicated module
  2. Define clear ownership
  3. Consume via explicit dependency
Model → Contract Coupling:
  1. Create integration-specific DTOs
  2. Map between internal models and DTOs at boundaries
  3. Version contracts independently of models
侵入式 → 契约式耦合
  1. 识别所有对实现细节的直接依赖
  2. 定义显式接口/契约
  3. 创建适配层
  4. 所有访问均通过适配层路由
功能式 → 模型式耦合
  1. 将共享业务逻辑提取到专用模块
  2. 明确所有权
  3. 通过显式依赖进行调用
模型式 → 契约式耦合
  1. 创建集成专用的DTO
  2. 在边界处映射内部模型与DTO
  3. 契约版本与模型独立管理

By Connascence Type

针对共生类型

FromToTechnique
CoM (Meaning)CoN (Name)Replace magic values with named constants/enums
CoP (Position)CoN (Name)Use named parameters, builder pattern, or parameter objects
CoA (Algorithm)CoN (Name)Extract algorithm to single location, reference by name
CoT (Type)CoN (Name)Use duck typing or interfaces
CoE (Execution)ExplicitUse state machines, builder pattern, or constructor injection
CoI (Identity)ExplicitUse dependency injection with explicit wiring
原类型目标类型技术手段
CoM(含义共生)CoN(名称共生)用命名常量/枚举替换魔法值
CoP(位置共生)CoN(名称共生)使用命名参数、构建器模式或参数对象
CoA(算法共生)CoN(名称共生)将算法提取到单一位置,通过名称引用
CoT(类型共生)CoN(名称共生)使用鸭子类型或接口
CoE(执行共生)显式控制使用状态机、构建器模式或构造函数注入
CoI(标识共生)显式控制使用依赖注入并显式配置

By Distance Problem

针对距离问题

High Strength + High Distance (Distributed Monolith):
  • Option A: Reduce distance—merge services/modules
  • Option B: Reduce strength—introduce contracts, async messaging
Low Strength + Low Distance (Over-abstraction):
  • Remove unnecessary abstraction layers
  • Inline overly generic code
  • Combine closely-related classes
高强度 + 远距离(分布式单体):
  • 选项A:缩短距离——合并服务/模块
  • 选项B:降低强度——引入契约、异步消息
低强度 + 近距离(过度抽象):
  • 移除不必要的抽象层
  • 内联过于通用的代码
  • 合并紧密相关的类

Analysis Workflow

分析流程

When asked to evaluate code modularization:
  1. Map the component structure
    • Identify modules, services, classes
    • Draw dependency graph
  2. Assess Integration Strength
    • For each dependency, classify: Intrusive/Functional/Model/Contract
    • Flag high-strength cross-boundary dependencies
  3. Measure Distance
    • Note component locations (same file → different systems)
    • Identify team/ownership boundaries
  4. Evaluate Volatility
    • Classify each component's subdomain type
    • Note historically frequently-changed areas
  5. Apply the formula
    • Check: Does strength match distance appropriately?
    • Does volatility excuse any mismatches?
  6. Identify Connascence
    • Scan for specific connascence types
    • Prioritize: high strength + low locality + high degree
  7. Recommend actions
    • Prioritize by impact and effort
    • Provide specific refactoring techniques
当需要评估代码模块化时,遵循以下步骤:
  1. 绘制组件结构
    • 识别模块、服务、类
    • 绘制依赖关系图
  2. 评估集成强度
    • 对每个依赖进行分类:侵入式/功能式/模型式/契约式
    • 标记跨边界的高强度依赖
  3. 测量距离
    • 记录组件位置(同一文件 → 不同系统)
    • 识别团队/所有权边界
  4. 评估易变性
    • 对每个组件的子域类型进行分类
    • 记录历史上频繁变更的区域
  5. 应用公式
    • 检查:强度与距离是否匹配?
    • 易变性是否能容忍不匹配?
  6. 识别共生类型
    • 扫描特定共生类型
    • 优先处理:高强度 + 低局部性 + 高程度的情况
  7. 提出建议
    • 按影响和工作量排序优先级
    • 提供具体的重构技术

Output Format

输出格式

Structure your evaluation as:
markdown
undefined
评估结果按以下结构组织:
markdown
undefined

Modularization Assessment

模块化评估报告

Summary

摘要

[Brief overview of coupling health]
[耦合健康状况的简要概述]

Component Map

组件映射

[Describe module/service structure]
[描述模块/服务结构]

Coupling Analysis

耦合分析

Component PairStrengthDistanceVolatilityBalance
A → BModelHighHigh
组件对强度距离易变性平衡状态
A → B模型式

Connascence Issues

共生问题

  1. [Specific connascence type]: [Location] - [Impact]
  1. [具体共生类型]:[位置] - [影响]

Recommendations

建议

  1. Priority 1: [Action] - [Rationale]
  2. Priority 2: [Action] - [Rationale]
  1. 优先级1:[行动] - [理由]
  2. 优先级2:[行动] - [理由]

Refactoring Plan

重构计划

[Step-by-step approach for highest-priority item]
undefined
[最高优先级项的分步实施方法]
undefined

References

参考资料

  • For detailed connascence examples: see
    references/connascence-types.md
  • For coupling metrics: see
    references/coupling-metrics.md
  • For refactoring patterns: see
    references/refactoring-patterns.md
  • 详细共生示例:参见
    references/connascence-types.md
  • 耦合指标:参见
    references/coupling-metrics.md
  • 重构模式:参见
    references/refactoring-patterns.md

Limitations

局限性

  • Cannot assess runtime behavior without execution context
  • Volatility assessment requires domain knowledge
  • Team/organizational distance requires project context
  • Historical change frequency not available from static analysis alone
  • 若无执行上下文,无法评估运行时行为
  • 易变性评估需要领域知识
  • 团队/组织层面的距离需要项目上下文
  • 仅通过静态分析无法获取历史变更频率