DRY Principle
Don't Repeat Yourself
Overview
DRY stands for "Don't Repeat Yourself". This principle states that every piece of knowledge or logic should have a single, unambiguous representation within a system.
Code duplication is one of the most common causes of bugs and maintenance headaches. When you need to change duplicated logic, you must remember to change it everywhere.
Key Concepts
Eliminate code duplication
Single source of truth
Extract common logic into reusable methods
Use inheritance or composition for shared behavior
Apply to code, data, and documentation
Code Example
1// ❌ BAD: Duplicated validation logic
2class UserService {
3 public void createUser(String email, String password) {
4 if (email == null || !email.contains("@")) {
5 throw new IllegalArgumentException("Invalid email");
6 }
7 if (password == null || password.length() < 8) {
8 throw new IllegalArgumentException("Password too short");
9 }
10 // Create user
11 }
12
13 public void updateUser(String email, String password) {
14 if (email == null || !email.contains("@")) { // Duplicated!
15 throw new IllegalArgumentException("Invalid email");
16 }
17 if (password == null || password.length() < 8) { // Duplicated!
18 throw new IllegalArgumentException("Password too short");
19 }
20 // Update user
21 }
22}
23
24// ✅ GOOD: DRY - Extract common validation
25class Validator {
26 public static void validateEmail(String email) {
27 if (email == null || !email.contains("@")) {
28 throw new IllegalArgumentException("Invalid email");
29 }
30 }
31
32 public static void validatePassword(String password) {
33 if (password == null || password.length() < 8) {
34 throw new IllegalArgumentException("Password too short");
35 }
36 }
37}
38
39class UserService {
40 public void createUser(String email, String password) {
41 Validator.validateEmail(email);
42 Validator.validatePassword(password);
43 // Create user
44 }
45
46 public void updateUser(String email, String password) {
47 Validator.validateEmail(email);
48 Validator.validatePassword(password);
49 // Update user
50 }
51}Validation logic is extracted to a Validator class. Changes to validation rules need to be made in only one place.
Advantages
- ✓
Easier maintenance - change once, affects everywhere
- ✓
Fewer bugs - no risk of inconsistent changes
- ✓
Better readability - less code to understand
- ✓
Easier testing - test once, trust everywhere
Best Practices
- 1.
Extract common code into methods or classes
- 2.
Use constants for magic numbers and strings
- 3.
Create utility classes for shared functionality
- 4.
Don't confuse similar-looking code with duplicate logic
- 5.
Balance DRY with code clarity - some duplication is acceptable
💡 Interview Tips
Give before/after example of refactoring
Mention it reduces bugs and maintenance effort
Discuss when duplication might be acceptable
Connect to Single Responsibility Principle