Java regex patterns - compile time constants or instance members?
- by KepaniHaole
Currently, I have a couple of singleton objects where I'm doing matching on regular expressions, and my Patterns are defined like so:
class Foobar {
private final Pattern firstPattern =
Pattern.compile("some regex");
private final Pattern secondPattern =
Pattern.compile("some other regex");
// more Patterns, etc.
private Foobar() {}
public static Foobar create() { /* singleton stuff */ }
}
But I was told by someone the other day that this is bad style, and Patterns should always be defined at the class level, and look something like this instead:
class Foobar {
private static final Pattern FIRST_PATTERN =
Pattern.compile("some regex");
private static final Pattern SECOND_PATTERN =
Pattern.compile("some other regex");
// more Patterns, etc.
private Foobar() {}
public static Foobar create() { /* singleton stuff */ }
}
The lifetime of this particular object isn't that long, and my main reason for using the first approach is because it doesn't make sense to me to hold on to the Patterns once the object gets GC'd.
Any suggestions / thoughts?