Overview

The Don’t Repeat Yourself (DRY) principle emphasizes that every piece of knowledge or logic should have a single, unambiguous representation in a system. By avoiding code duplication, DRY improves maintainability, reduces errors, and ensures consistency across a codebase. In FAANG interviews, adherence to DRY demonstrates a candidate’s ability to write clean, efficient code that scales well in large systems.


Definition

DRY requires centralizing logic to avoid redundancy. When the same logic appears in multiple places, any change must be replicated across all instances, increasing the risk of inconsistencies and bugs. DRY ensures that logic is defined once and reused, making code easier to maintain and modify.

Why It Matters

In large-scale systems, duplicated code leads to maintenance nightmares, as developers must update multiple locations when requirements change. DRY ensures that changes are made in one place, reducing errors and improving collaboration in team environments, a common scenario at FAANG companies.

Real-World Analogy

Consider a recipe book with multiple recipes repeating the same steps for making a sauce. If the sauce recipe changes, every recipe must be updated, risking inconsistencies. Centralizing the sauce recipe in one place ensures uniformity and simplifies updates.

Bad Code Example

emme

class SubmitButton {
    void render() {
        System.out.println("Apply rounded corners");
        System.out.println("Set background color to blue");
        System.out.println("Submit action");
    }
}

class CancelButton {
    void render() {
        System.out.println("Apply rounded corners");
        System.out.println("Set background color to blue");
        System.out.println("Cancel action");
    }
}

Issues:

Good Code Example

abstract class Button {
    void render() {
        applyStyle();
        performAction();
    }
    protected void applyStyle() {
        System.out.println("Apply rounded corners");
        System.out.println("Set background color to blue");
    }
    abstract void performAction();
}

class SubmitButton extends Button {
    void performAction() { System.out.println("Submit action"); }
}

class CancelButton extends Button {
    void performAction() { System.out.println("Cancel action"); }
}

Improvements: