What is the DRY Principle?
The DRY (Don't Repeat Yourself) principle is one of the fundamental concepts in programming, aimed at reducing code repetition. It suggests that repeated segments of data, logic, or functionality should be reused rather than duplicated across different parts of the code.
Why is DRY Important?
- Code Readability – Reduces redundant code, making it easier to understand.
- Maintainability – Changes are made in one place without affecting multiple sections.
- Maintenance – Reduces the likelihood of errors since the same functionality is managed in one place.
Examples of Bad and Good Practices
❌ Bad Example (Repeated Code)
function calculateAreaRectangle(width: number, height: number): number {
return width * height;
}
function calculateAreaSquare(side: number): number {
return side * side;
}
✅ Good Example (DRY Approach)
function calculateArea(shape: { width?: number; height?: number; side?: number }): number {
if (shape.side) {
return shape.side * shape.side;
}
if (shape.width && shape.height) {
return shape.width * shape.height;
}
throw new Error("Invalid shape parameters");
}
In this case, the same function handles two different calculations, avoiding repeated code.
How to Apply DRY
- Use Functions and Modules – Turn repeated code into reusable functions or modules.
- Use Classes and Inheritance – If you have common properties, they can be grouped into classes.
- Use Configuration Instead of Data – Whenever possible, functionality should depend on parameters rather than duplicated code.
Potential Drawbacks (Over-Abstraction)
Although DRY is a useful principle, it can lead to over-abstraction, where the code becomes overly complex in an attempt to eliminate all repetition. It is important to maintain a balance and not make the code too generic.