DRY Principle
They are guidelines that help software developers create system that are easy to understand, maintain, and extend. They are applied both at high-level and low-level design stages.
DRY: Don't Repeat Yourself
It states that every piece of knowledge must have a single, unambiguous, authoritative representation within the system. In simple terms, avoid duplication of logic or code.
Importance
- Reduces Redundancy
- Easier Maintainence
- Single Point of Change
How to Apply
- Identify repetitive code
- Extract the Common functionality and write it as a reusable function/component
- Leverage libraries and frameworks when available
- Refactor duplicate logic regularly across classes or layers
Example
Bad Code
import java.util.*;class Main { public static void main(String[] args){ int length1 = 10, width1 = 5; int area1 = length1 * width1; System.out.println("Area1: ", + area1); int length2 = 8, width2 = 4; int area2 = length2 * width2; System.out.println("Area2: ", + area2); }}In the above code, logic for calculating area is repeated in both the print statements. If we need to change the logic, we have to do it in multiple places.
Refactored Good Code
import java.util.*;class AreaCalculator{ public static int calculateArea(int length, int width){ return length * width; }}class Main { public static void main(String[] args){ int area1 = AreaCalculator.calculateArea(10, 5); int area2 = AreaCalculator.calculateArea(8, 4); System.out.println("Area1: " + area1); System.out.println("Area2: " + area2); }}In refactored code, we created a single method calculateArea that calculates area. Now, if we need to change the logic, we have to do it in one place.
When Not to Use
-
Premature Abstraction:
- Don't extract common code to early. At first it may look the same, but later could change in different ways
- Extracting them into a shared method can create unnecessary coupling between unrelated parts
-
Performance-Critical Code
-
Sacrificing Readability: If extracting repeated code makes code less readable, prefer clarity over DRYness
-
Legacy Codebases