Skip to main content

Hardcoded Variability

Description

What does it look like?

  • The variable part of the logic is hardcoded directly and not separated from the fixed part
  • “Slightly different” behaviors are mixed into a common flow, making reuse difficult
  • Even though the overall flow is the same, the entire logic is duplicated for small differences

Why is it a problem?

  • Without clear separation between shared and differing parts, changes are hard to make
  • Similar but slightly different code grows, increasing the risk of bugs and maintenance overhead
  • The code lacks flexibility, making feature extension and switching difficult

Bad Example of the Anti-pattern

class NotificationService {
sendEmail(user: string, message: string) {
console.log(`件名: お知らせ`);
console.log(`本文: ${message}`);
console.log(`宛先: ${user}@example.com`);
}

sendSlack(user: string, message: string) {
console.log(`Slack宛: ${user}`);
console.log(`内容: ${message}`);
}
}

Issues:

  • Email and Slack notifications mix shared structure with their differences
  • Every time a new channel (e.g., LINE, SMS) is added, similar methods are created again
  • The shared logic becomes cluttered, resulting in poor testability and maintainability

Refactoring by Pattern

Design patterns that can address this

PatternOverviewMain Refactoring Approach
Template MethodStandardize the flow and define differences in subclassesPrevent duplication and improve reusability
StrategyAllow behavior to be swappedEasier to replace and test
BridgeSeparate abstraction from implementationClarify axes of change and enable flexibility
FlyweightShare common state to reduce object countMinimize redundant data
PrototypeClone instances from a templateReuse initialization and generate variations efficiently