Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't "static" patterns always be static?

I just found a bug in some code I didn't write and I'm a bit surprised:

Pattern pattern = Pattern.compile("\\d{1,2}.\\d{1,2}.\\d{4}"); Matcher matcher = pattern.matcher(s); 

Despite the fact that this code fails badly on input data we get (because it tries to find dates in the 17.01.2011 format and gets back things like 10396/2011 and then crashed because it can't parse the date but that really ain't the point of this question ; ) I wonder:

  • isn't one of the point of Pattern.compile to be a speed optimization (by pre-compiling regexps)?

  • shouldn't all "static" pattern be always compiled into static pattern?

There are so many examples, all around the web, where the same pattern is always recompiled using Pattern.compile that I begin to wonder if I'm seeing things or not.

Isn't (assuming that the string is static and hence not dynamically constructed):

static Pattern pattern = Pattern.compile("\\d{1,2}.\\d{1,2}.\\d{4}"); 

always preferrable over a non-static pattern reference?

like image 914
Gugussee Avatar asked Feb 08 '11 15:02

Gugussee


People also ask

Why you shouldn't use static methods?

Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.

Should static be avoided?

Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.

Should methods be static if possible Java?

To answer the question on the title, in general, Java methods should not be static by default. Java is an object-oriented language.

Is pattern class thread safe?

Instances of this (Pattern) class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not safe for such use.


1 Answers

  1. Yes, the whole point of pre-compiling a Pattern is to only do it once.
  2. It really depends on how you're going to use it, but in general, pre-compiled patterns stored in static fields should be fine. (Unlike Matchers, which aren't threadsafe and therefore shouldn't really be stored in fields at all, static or not.)

The only caveat with compiling patterns in static initializers is that if the pattern doesn't compile and the static initializer throws an exception, the source of the error can be quite annoying to track down. It's a minor maintainability problem but it might be worth mentioning.

like image 89
biziclop Avatar answered Sep 22 '22 21:09

biziclop