Skip to content

Recipe to avoid calling Pattern.compile() too many times #622

Description

@greg-at-moderne

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status
    Recipes Wanted

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions