What problem are you trying to solve?
Efficiency.
It's a typical and suggested pattern to have Regular Expressions constructed as constants in classes. As opposed to calling Pattern.compile("SOMETHING") or similar over and over again.
What precondition(s) should be checked before applying this recipe?
The recipe should kick in only if the argument is a literal or maybe other hard-coded constant.
In some rare cases one can imagine constructing the regexp programmatically, then there's little chance for immediate optimization.
Describe the situation before applying the recipe
public class EmailValidator {
public static boolean isValidEmail(String email) {
Pattern pattern = Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$");
return pattern.matcher(email).matches();
}
}
Describe the situation after applying the recipe
public class EmailValidator {
private static final Pattern EMAIL_PATTERN =
Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$");
public static boolean isValidEmail(String email) {
return EMAIL_PATTERN.matcher(email).matches();
}
}
Context
- as far as I recall, there are other methods for constructing regular expressions in Java, they should be covered too
What problem are you trying to solve?
Efficiency.
It's a typical and suggested pattern to have Regular Expressions constructed as constants in classes. As opposed to calling
Pattern.compile("SOMETHING")or similar over and over again.What precondition(s) should be checked before applying this recipe?
The recipe should kick in only if the argument is a literal or maybe other hard-coded constant.
In some rare cases one can imagine constructing the regexp programmatically, then there's little chance for immediate optimization.
Describe the situation before applying the recipe
Describe the situation after applying the recipe
Context