refactor-method-complexity-reduce

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Refactor Method to Reduce Cognitive Complexity

重构方法以降低认知复杂度

Objective

目标

Refactor the method
${input:methodName}
, to reduce its cognitive complexity to
${input:complexityThreshold}
or below, by extracting logic into focused helper methods.
${input:methodName}
方法重构,通过将逻辑提取到专注的辅助方法中,使其认知复杂度降低至
${input:complexityThreshold}
或以下。

Instructions

操作步骤

  1. Analyze the current method to identify sources of cognitive complexity:
    • Nested conditional statements
    • Multiple if-else or switch chains
    • Repeated code blocks
    • Multiple loops with conditions
    • Complex boolean expressions
  2. Identify extraction opportunities:
    • Validation logic that can be extracted into a separate method
    • Type-specific or case-specific processing that repeats
    • Complex transformations or calculations
    • Common patterns that appear multiple times
  3. Extract focused helper methods:
    • Each helper should have a single, clear responsibility
    • Extract validation into separate
      Validate*
      methods
    • Extract type-specific logic into handler methods
    • Create utility methods for common operations
    • Use appropriate access levels (static, private, async)
  4. Simplify the main method:
    • Reduce nesting depth
    • Replace massive if-else chains with smaller orchestrated calls
    • Use switch statements where appropriate for cleaner dispatch
    • Ensure the main method reads as a high-level flow
  5. Preserve functionality:
    • Maintain the same input/output behavior
    • Keep all validation and error handling
    • Preserve exception types and error messages
    • Ensure all parameters are properly passed to helpers
  6. Best practices:
    • Make helper methods static when they don't need instance state
    • Use null checks and guard clauses early
    • Avoid creating unnecessary local variables
    • Consider using tuples for multiple return values
    • Group related helper methods together
  1. 分析当前方法以找出认知复杂度的来源:
    • 嵌套条件语句
    • 多个if-else或switch分支链
    • 重复的代码块
    • 带有条件的多重循环
    • 复杂的布尔表达式
  2. 识别可提取的机会
    • 可提取到独立方法中的验证逻辑
    • 重复出现的特定类型或特定场景处理逻辑
    • 复杂的转换或计算逻辑
    • 多次出现的通用模式
  3. 提取专注的辅助方法
    • 每个辅助方法应具备单一、明确的职责
    • 将验证逻辑提取到独立的
      Validate*
      方法中
    • 将特定类型的逻辑提取到处理方法中
    • 为通用操作创建工具方法
    • 使用合适的访问级别(static、private、async)
  4. 简化主方法
    • 减少嵌套层级
    • 用小型的编排调用替代庞大的if-else链
    • 在合适的场景下使用switch语句以实现更清晰的分发
    • 确保主方法呈现为高层级的流程
  5. 保留原有功能
    • 维持相同的输入/输出行为
    • 保留所有验证和错误处理逻辑
    • 保留异常类型和错误消息
    • 确保所有参数都正确传递给辅助方法
  6. 最佳实践
    • 当辅助方法不需要实例状态时,将其设为static
    • 尽早使用空值检查和守卫子句
    • 避免创建不必要的局部变量
    • 考虑使用元组来返回多个值
    • 将相关的辅助方法分组存放

Implementation Approach

实现方法

  • Extract helper methods before refactoring the main flow
  • Test incrementally to ensure no regressions
  • Use meaningful names that describe the extracted responsibility
  • Keep extracted methods close to where they're used
  • Consider making repeated code patterns into generic methods
  • 在重构主流程之前先提取辅助方法
  • 逐步测试以确保没有回归问题
  • 使用能描述提取职责的有意义的名称
  • 让提取的方法靠近其使用位置
  • 考虑将重复的代码模式转化为通用方法

Result

预期结果

The refactored method should:
  • Have cognitive complexity reduced to the target threshold of
    ${input:complexityThreshold}
    or below
  • Be more readable and maintainable
  • Have clear separation of concerns
  • Be easier to test and debug
  • Retain all original functionality
重构后的方法应:
  • 认知复杂度降低至目标阈值
    ${input:complexityThreshold}
    或以下
  • 具备更高的可读性和可维护性
  • 实现清晰的关注点分离
  • 更易于测试和调试
  • 保留所有原有功能

Testing and Validation

测试与验证

CRITICAL: After completing the refactoring, you MUST:
  1. Run all existing tests related to the refactored method and its surrounding functionality
  2. MANDATORY: Explicitly verify test results show "failed=0"
    • NEVER assume tests passed - always examine the actual test output
    • Search for the summary line containing pass/fail counts (e.g., "passed=X failed=Y")
    • If the summary shows any number other than "failed=0", tests have FAILED
    • If test output is in a file, read the entire file to locate and verify the failure count
    • Running tests is NOT the same as verifying tests passed
    • Do not proceed until you have explicitly confirmed zero failures
  3. If any tests fail (failed > 0):
    • State clearly how many tests failed
    • Analyze each failure to understand what functionality was broken
    • Common causes: null handling, empty collection checks, condition logic errors
    • Identify the root cause in the refactored code
    • Correct the refactored code to restore the original behavior
    • Re-run tests and verify "failed=0" in the output
    • Repeat until all tests pass (failed=0)
  4. Verify compilation - Ensure there are no compilation errors
  5. Check cognitive complexity - Confirm the metric is at or below the target threshold of
    ${input:complexityThreshold}
重要提示:完成重构后,您必须执行以下操作:
  1. 运行所有与重构方法及其相关功能相关的现有测试
  2. 必须:明确验证测试结果显示"failed=0"
    • 绝不要假设测试通过 - 务必检查实际的测试输出
    • 查找包含通过/失败计数的汇总行(例如:"passed=X failed=Y")
    • 如果汇总显示失败数不为"0",则测试未通过
    • 如果测试输出在文件中,请完整读取文件以定位并验证失败计数
    • 运行测试并不等同于验证测试通过
    • 在明确确认失败数为0之前,请勿继续
  3. 如果有任何测试失败(failed > 0):
    • 明确说明有多少个测试失败
    • 分析每个失败案例以了解哪些功能被破坏
    • 常见原因:空值处理、空集合检查、条件逻辑错误
    • 在重构后的代码中找出根本原因
    • 修改重构后的代码以恢复原有行为
    • 重新运行测试并验证输出中显示"failed=0"
    • 重复此过程直到所有测试通过(failed=0)
  4. 验证编译情况 - 确保没有编译错误
  5. 检查认知复杂度 - 确认该指标达到或低于目标阈值
    ${input:complexityThreshold}

Confirmation Checklist

确认清单

  • Code compiles without errors
  • Test results explicitly state "failed=0" (verified by reading the output)
  • All test failures analyzed and corrected (if any occurred)
  • Cognitive complexity is at or below the target threshold of
    ${input:complexityThreshold}
  • All original functionality is preserved
  • Code follows project conventions and standards
  • 代码编译无错误
  • 测试结果明确显示"failed=0"(已通过读取输出验证)
  • 所有测试失败案例均已分析并修正(如有)
  • 认知复杂度达到或低于目标阈值
    ${input:complexityThreshold}
  • 所有原有功能均被保留
  • 代码遵循项目约定和标准