Java regex patterns - compile time constants or instance members?

Posted by KepaniHaole on Programmers See other posts from Programmers or by KepaniHaole
Published on 2013-11-02T19:44:47Z Indexed on 2013/11/03 4:11 UTC
Read the original article Hit count: 347

Filed under:
|

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?

© Programmers or respective owner

Related posts about java

Related posts about regex