Back to Catalog
Code Smells
Dispensables
Duplicate Code
The same or similar code appears in multiple places.
Intent & Description
'
🎯 Intent
Identify and eliminate code duplication. Duplicated code makes maintenance difficult and increases the risk of inconsistencies.
📋 Context
You find identical or very similar code blocks in multiple locations. When bugs are found or requirements change, you must update the same logic in multiple places.
💡 Solution
Extract duplicated code into reusable functions, classes, or modules. Apply DRY principle to create single sources of truth for shared logic.'
Real-world Use Case
Use when you identify identical code blocks, when you make the same changes in multiple files, or when you copy-paste code frequently.
Source
📌 TL;DR
Duplicate code is maintenance nightmare. Extract repeated logic into reusable abstractions. Apply DRY principle consistently.
Advantages
- Single source of truth
- Easier maintenance and updates
- Reduced risk of inconsistencies
Disadvantages
- Can lead to over-abstraction
- May require careful parameterization
Implementation Example
// Before: Duplicate code
function calculateArea(shape) {
if (shape.type === 'circle') {
return Math.PI * shape.radius * shape.radius;
} else if (shape.type === 'rectangle') {
return shape.width * shape.height;
}
}
function calculatePerimeter(shape) {
if (shape.type === 'circle') {
return 2 * Math.PI * shape.radius;
} else if (shape.type === 'rectangle') {
return 2 * (shape.width + shape.height);
}
}
// After: Extracted logic
class Circle {
constructor(radius) {
this.radius = radius;
}
area() {
return Math.PI * this.radius * this.radius;
}
perimeter() {
return 2 * Math.PI * this.radius;
}
}
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
perimeter() {
return 2 * (this.width + this.height);
}
}