DRY (Don’t Repeat Yourself) is a principle focused on knowledge duplication, not code duplication.

Core Concept

The DRY principle states that two identical pieces of code may represent different business knowledge with different reasons to change. Removing duplication without understanding knowledge boundaries can introduce risk.

Knowledge vs Code Duplication

The Don’t Repeat Yourself (DRY) principle is not about duplicated code.

If two identical pieces of code represent different business knowledge, then they might have different reasons to change.

They may need to change independently. Removing such duplication can introduce risk.

If two pieces of code represent the same knowledge, then they are bound to change together, so we can safely remove the duplication.

DRY is about knowledge duplication, not code.

When to Apply DRY

  • Rule of Three: Consider abstraction only after seeing the same pattern at least 3 times
  • AHA (Avoid Hasty Abstractions): Don’t create abstractions prematurely
  • Ensure duplicated code actually represents the same business knowledge
  • Verify that changes would need to happen together

When NOT to Apply DRY

  • Code happens to look similar but serves different business purposes
  • Changes are unlikely to happen together
  • The abstraction would be more complex than the duplication

Resources

References