DRY in Java

🚨 Without DRY (Bad Practice – Code Duplication)

public class Calculator {

    // Duplicated logic for addition
    public int addIntegers(int a, int b) {
        return a + b;
    }

    // Duplicated logic for doubles
    public double addDoubles(double a, double b) {
        return a + b;
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.addIntegers(2, 3));
        System.out.println(calc.addDoubles(2.5, 3.7));
    }
}

🔴 Problem: The addition logic is duplicated for integers and doubles. If we want to extend to float, long, etc., duplication keeps increasing.


✅ With DRY (Good Practice – Reusable Code)

Example 1: Using Generics

public class Calculator {

    // DRY: Generic method for addition
    public <T extends Number> double add(T a, T b) {
        return a.doubleValue() + b.doubleValue();
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(2, 3));       // int
        System.out.println(calc.add(2.5, 3.7));   // double
        System.out.println(calc.add(5L, 10L));    // long
    }
}

✅ One method works for all number types → no duplication.


Example 2: Extracting Reusable Logic

public class AreaCalculator {

    // DRY: Common reusable method
    public double calculateArea(double length, double width) {
        return length * width;
    }

    public static void main(String[] args) {
        AreaCalculator calc = new AreaCalculator();

        // Rectangle
        System.out.println("Rectangle Area: " + calc.calculateArea(5, 10));

        // Square (uses same method)
        System.out.println("Square Area: " + calc.calculateArea(6, 6));
    }
}

✅ Instead of writing separate methods for rectangle and square, we reuse one method.


👉 Summary:

  • DRY in Java means removing duplicate logic by using methods, classes, generics, inheritance, or interfaces.
  • This makes the code shorter, easier to maintain, and less error-prone.

Leave a Reply