Code Quality
Duplicate Code in Java: How to Apply the DRY Principle
Duplicate code in Java is a pervasive issue in large codebases. The same validation, calculation, or algorithm in multiple service classes causes divergence when rules change.
❌ Duplicated Validation
public class UserService {
public void createUser(String email, String name) {
if (email == null || !email.contains('@')) throw new ValidationException('Invalid email');
if (name == null || name.length() < 2) throw new ValidationException('Name too short');
}
}
public class AdminService {
public void createAdmin(String email, String name) {
if (email == null || !email.contains('@')) throw new ValidationException('Invalid email'); // Duplicate!
if (name == null || name.length() < 2) throw new ValidationException('Name too short'); // Duplicate!
}
}✅ Shared Validator
public class UserValidator {
public static void validateEmail(String email) {
if (email == null || !email.contains('@'))
throw new ValidationException('Invalid email');
}
public static void validateName(String name) {
if (name == null || name.length() < 2)
throw new ValidationException('Name too short');
}
}
// Both services call UserValidator.validateEmail/Name💡
Pro tip: PMD's CPD (Copy-Paste Detector) finds duplicated code blocks: mvn pmd:cpd. Run it in CI to prevent new duplication.
Paste this code into LearnCodeGuide
Detect Java vulnerabilities and bugs automatically with AI-powered analysis.
Analyze Java Code →