DRY Principle
Don't Repeat Yourself Principle
DRY stand for "Don't Repeat Yourself," a basic principle of software development aimed at reducing the repetition of information. The DRY principle is stated as, "Every piece of knowledge or logic must have a single, unambiguous representation within a system."
Structured programming, Aspect Oriented Programming, Component Oriented Programming, and Design Patterns are all, in part, strategies for eliminating duplication.
Duplication manifests itself in many forms:
Lines of code that look exactly the same.
Lines of code that are similar to.
Duplication of implementation.
Example of "exactly the same"
class UserService {
public void createUser(String email, String password) {
if (isEmailValid(email)) {
// create user
}
}
private boolean isEmailValid(String email) {
String pattern = "email pattern";
Pattern pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
}
class SubscriptionService {
public void subscribe(String topic, String email) {
if (isEmailValid(email)) {
// subscribe
}
}
// By copying and pasting an existing class,
// we have introduced some duplicated code in the codebase.
private boolean isEmailValid(String email) {
String pattern = "email pattern";
Pattern pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
}Example of "similar to"
The Template Method Pattern is a common technique for removing higher-level duplication.
Example of "duplication of implementation"
Solutions: using Generic class or AOP.
Last updated