Skip to main content

Duplicated Logic

Description

What does it look like?

  • Similar logic is copy-pasted in multiple places
  • Slight variations are manually modified after duplicating a base implementation
  • Although it may look readable, maintainability and consistency are compromised

Why is it a problem?

  • When changes are needed, every copy must be found and updated
  • If even one is missed, it can lead to bugs
  • Increases the effort for testing and code reviews, reducing overall reliability

Bad Example of the Anti-pattern

class PdfExporter {
export(data: string) {
console.log("開始ログ");
console.log(`PDF出力: ${data}`);
console.log("完了ログ");
}
}

class CsvExporter {
export(data: string) {
console.log("開始ログ");
console.log(`CSV出力: ${data}`);
console.log("完了ログ");
}
}

class XmlExporter {
export(data: string) {
console.log("開始ログ");
console.log(`XML出力: ${data}`);
console.log("完了ログ");
}
}

Issues:

  • All exporters repeat the same start and finish logging
  • The only variation is the output logic, yet the full structure is rewritten every time
  • Any change to logging or formatting must be reflected across all exporters

Refactoring by Pattern

Design patterns that can address this

PatternOverviewMain Refactoring Approach
Template MethodStandardize flow and define only differences in subclassesCentralize the “template” of processing
StrategyInject the varying behavior externallyEnable dynamic swapping of logic
DecoratorWrap and add or override functionalityStack reusable enhancements around core behavior
VisitorSeparate logic from data structureExternalize logic to support multiple output formats
PrototypeClone instances from a templateReplace manual rewriting with instance duplication