DRY Code
Classes that repeat the same variables and methods break the DRY principle, and merging them into one class is not the answer.
Novice · Java · OOP · Updated
With encapsulation, our focus is on grouping related variables and methods into classes. Our goal is to organize our data and logic into objects/classes which have well-defined responsibilities.
You may have noticed that as you design classes, some classes share similar variable names or have methods with the same names or logic. When this happens, your code violates the DRY principle (Don’t Repeat Yourself).
The following classes might exist in an adventure game that you are programming. You may have a general Character and 3 special types of characters: Archer, Wizard, and Knight.
Notice that all character types have many variables and methods in common. For example, all characters have a name, health, level and experience. Additionally, all characters can attack, takeDamage, levelUp, and use a specialAbility. The methods in blue indicate that the logic in those methods is slightly different than the original method in the Character class.

We need to find a way to remove duplicate code. One option would be to combine all classes into a single class.

In this example, we have removed the duplicate code and have put all variables that could be needed into the same character class.
- type: this determines the type of character
- arrows: this is only used by an archer type
- mana: this is only used by a wizard type
- armor: this is only used by a knight type
The methods are also character-type specific. The green methods are ones that each character type has, but the logic changes based on the character type. This means that we must have if-then logic to determine what logic to execute.
Also, this class is no longer cohesive. Since arrows is only used by an archer, that variable is unused for every other character type. The same is true for armor, which is only used for the knight character type. In other words, this is a bad solution.
Do it: write the status line once
The adventure game shows a character's status line in many places: after a level-up, after a battle, on the save screen. Right now each place builds the line itself, so changing its format means finding every copy. Write the format once, in one method, and every place can call it.
The method gets three values:
name: the character's name, such as"Robin".level: the character's level, such as2.health: the character's health, such as110.
For example, statusLine("Robin", 2, 110) returns "Robin: level 2, health 110".
Your job: write the method statusLine(String name, int level, int health) so it returns that line, a String, for any character.
- The name, then
: level, then the level. - Then
, health, then the health.
The starter's main() shows three places in the game that will use it. Leave it as it is.
Practiced live on the lesson page: write the Java right there and check it.