~/wiki

Code Duplication Risks

Confiance : medium
code-duplicationsoftware-maintenancetechnical-debtsql-generationconsistency-risksrefactoringdry-principle

Software engineering anti-pattern where identical or similar logic is implemented multiple times across a codebase, creating maintenance burdens and consistency risks that compound over time.

Core Problems

Inconsistent Updates: When business logic changes, developers must locate and update all duplicate implementations, often missing some instances.

Bug Multiplication: Defects in duplicated code must be fixed in multiple locations, increasing the probability of incomplete fixes.

Testing Overhead: Each duplicate implementation requires separate test coverage instead of shared validation.

Cognitive Load: Developers must understand multiple implementations of the same concept, slowing development velocity.

SQL Generation Example

The assistant-rh project demonstrated classic duplication risks with SQL generation:

  • Unused Method: _build_select_sql was implemented but never called
  • Duplicated Logic: SQL construction was reimplemented inline with different conditional paths
  • Maintenance Risk: Changes to SQL structure required updates in multiple locations
  • Column Inconsistency: Different implementations might forget columns or filters

Detection Strategies

Static Analysis: Tools like PMD, SonarQube, or custom scripts can identify similar code blocks automatically.

Code Review Focus: Explicitly check for duplication during review, especially when adding new conditional branches.

Architectural Patterns: Use factory methods, strategy patterns, or builder patterns to centralize logic.

Refactoring Cycles: Regular technical debt sessions to consolidate identified duplications.

Mitigation Approaches

Extract Common Methods: Move shared logic into reusable functions with clear parameters and contracts.

Template Method Pattern: Define abstract algorithms with customizable steps rather than duplicating entire implementations.

Configuration-Driven Logic: Replace conditional branches with data-driven approaches using configuration files or lookup tables.

Builder Patterns: For complex construction like SQL queries, use fluent builders that ensure consistency across all usage sites.

Prevention

DRY Principle: "Don't Repeat Yourself" - abstract common patterns as soon as duplication is identified.

Single Responsibility: Keep methods focused on one task to make extraction and reuse easier.

Code Review Standards: Establish team standards that flag duplication as blocking review issues.

Architectural Guidelines: Design systems with clear separation of concerns to reduce the temptation for duplication.

See also