Back to Catalog
Dry Yagni
principles
Don't Repeat Yourself (DRY)
Every piece of knowledge must have a single, unambiguous representation within a system.
Intent & Description
'
🎯 Intent
Avoid duplication of logic and data. Every piece of knowledge should have a single, authoritative representation in the system.
📋 Context
You find yourself copying and pasting code, writing similar functions with slight variations, or maintaining the same logic in multiple places. When bugs are found, you have to fix them in multiple locations.
💡 Solution
Identify repeated code and extract it into reusable functions, classes, or modules. Create abstractions that capture the common logic and parameterize the differences.'
Real-world Use Case
Use when you identify duplicated code, when you need to make similar changes in multiple places, or when you want to reduce maintenance burden.
📌 TL;DR
Don’t repeat yourself. Extract duplication into reusable abstractions. Reduces maintenance burden and inconsistencies.
Advantages
- Reduced code duplication
- Easier maintenance and updates
- Consistent behavior across codebase
- Reduced risk of inconsistencies
Disadvantages
- Can lead to over-abstraction
- May increase complexity for simple cases
- Premature extraction can create rigid code
Implementation Example
// Before: Duplicated code
function calculateCircleArea(radius) {
return Math.PI * radius * radius;
}
function calculateSphereVolume(radius) {
return (4/3) * Math.PI * radius * radius * radius;
}
function calculateCylinderVolume(radius, height) {
return Math.PI * radius * radius * height;
}
// After: DRY applied
function calculatePIRadiusSquared(radius) {
return Math.PI * radius * radius;
}
function calculateCircleArea(radius) {
return calculatePIRadiusSquared(radius);
}
function calculateSphereVolume(radius) {
return (4/3) * calculatePIRadiusSquared(radius) * radius;
}
function calculateCylinderVolume(radius, height) {
return calculatePIRadiusSquared(radius) * height;
}