DRY (Don't Repeat Yourself)
DRY (Don't Repeat Yourself) Principle in Programming
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.
❌ 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.
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.