DRY Principle
Overview
DRY means Do Not Repeat Yourself. Knowledge should have a single, authoritative representation in a codebase.
Why DRY Matters
Duplicate logic increases maintenance cost and bug risk. A change applied to one copy but missed in another introduces inconsistent behavior.
flowchart TD
A[Duplicate Logic] --> B[Inconsistent Fixes]
B --> C[Production Defects]
D[Shared Abstraction] --> E[Single Update Point]
E --> F[Consistent Behavior]
Practical Example
Validation duplicated across services:
// service A
if (!email.Contains("@")) throw new ArgumentException("Invalid email");
// service B
if (!email.Contains("@")) throw new ArgumentException("Invalid email");
Refactor into shared utility:
public static class EmailValidator
{
public static void ValidateEmail(string email)
{
if (!email.Contains("@"))
{
throw new ArgumentException("Invalid email");
}
}
}
Production Guidance
- Share rules through libraries or domain modules
- Keep shared code versioned and documented
- Avoid coupling unrelated modules through oversized utility packages
Common Pitfalls
- Premature abstraction for patterns that are not stable
- Merging different concerns into one generic helper
- Ignoring domain boundaries while deduplicating
Key Takeaways
- DRY reduces inconsistency and maintenance overhead.
- Stable duplication signals a refactoring opportunity.
- Abstractions should reflect real domain commonality.