Skip to main content

Section 8.2 The DRY Principle: Avoiding Repeated Code

In software development, repeating similar code across multiple classes can lead to significant issues. Consider a game that has multiple character types, such as Player, Monster, and NPC,each requiring common attributes like health and methods like takeDamage(). Without applying any reuse principles, your code might look like this:
public class Player {
    private int health;

    public void takeDamage(int amount) {
        health -= amount;
    }
}

public class Monster {
    private int health;

    public void takeDamage(int amount) {
        health -= amount;
    }
}

public class NPC {
    private int health;

    public void takeDamage(int amount) {
        health -= amount;
    }
}
Notice how the takeDamage() method and health field are identical in each class. Duplicating code this way is risky because:
  • You must remember to update each class if the logic changes, which increases maintenance burden.
  • It’s easy to introduce inconsistencies or errors if you miss updating one class.
  • The codebase quickly becomes bloated and difficult to manage.
The DRY principle (Don’t Repeat Yourself) advises avoiding this duplication by identifying and abstracting common behaviors into a single, shared implementation.
Inheritance directly addresses the DRY principle by creating a shared parent class:
// Parent class with shared functionality
public class GameEntity {
    protected int health;
    
    public void takeDamage(int amount) {
        health -= amount;
    }
}

// Subclasses inherit common behavior and add specifics
public class Player extends GameEntity {
    private int experiencePoints;
    
    public void gainExperience(int amount) {
        experiencePoints += amount;
    }
}

public class Monster extends GameEntity {
    private boolean isAggressive;
    
    public void setAggressive(boolean aggressive) {
        isAggressive = aggressive;
    }
}

Note 8.2.1.

While these examples show identical code duplication, inheritance is most appropriate when the duplicated elements represent a genuine specialization relationship. When shared behavior might evolve differently across classes or when the "is-a" relationship doesn’t hold, consider alternatives like interfaces or composition.
For example, while a Monster genuinely is a GameEntity, a Game is not a Player it contains or manages players. Consider this example of inappropriate inheritance:
// Inappropriate inheritance example
public class Game extends Player {
    private List<Monster> monsters;
    
    // Game methods...
}
This design is problematic because a Game is not a specialized type of Player, yet it would inherit player-specific attributes like health and experience that don’t make sense for a game. Additionally, changes to the Player class would unexpectedly affect the Game class. A better approach would use composition: Game would contain instances of Player, Monster, and other game elements.
Check Your Understanding

Checkpoint 8.2.2.

Which statement best describes the DRY (Don’t Repeat Yourself) principle?
  • Every piece of knowledge should have a single, unambiguous representation in a system.
  • Correct! Every piece of knowledge should have a single, unambiguous representation in a system.
  • Code should be duplicated whenever necessary to improve readability.
  • Methods should always be rewritten in every new class instead of inherited.
  • DRY only applies to database design, not to programming.

Checkpoint 8.2.3.

How does the DRY (Don’t Repeat Yourself) principle relate to inheritance in Java?
  • Inheritance reduces code duplication by allowing subclasses to reuse methods and attributes from a superclass.
  • Correct! Inheritance reduces code duplication by allowing subclasses to reuse methods and attributes from a superclass.
  • Inheritance forces all subclasses to implement the same methods, ensuring uniformity.
  • Inheritance prevents code reuse by restricting access to superclass methods.
  • Inheritance eliminates the need for method overriding in subclasses.
You have attempted of activities on this page.