I've been reviewing Java Regex
Library, surprised by the fact the Pattern
class does not have a public constructor which I've taken for granted for years.
One reason I suspect the static compile
method is being used in favor of constructor could be that constructor would always return a new object while a static method might return a previously created (and cached) object provided that the pattern string is the same.
However, it is not the case as demonstrated by the following.
public class PatternCompiler {
public static void main(String[] args) {
Pattern first = Pattern.compile(".");
Pattern second = Pattern.compile(".");
if (first == second) {
System.out.println("The same object has been reused!");
} else {
System.out.println("Why not just use constructor?");
}
}
}
Any other strong rationales behind using static method over constructor?
Edit: I found a related question here. None of the answers there convinced me either. Reading through all answers, I get a feeling that a static method has quite a few advantages over a public constructor regarding creating an object but not the other way around. Is that true? If so, I'm gonna create such static methods for each one of my classes and safely assume that it's both more readable and flexible.
Generally, a class won't have a public constructor for one of three reasons:
null
.In the class of Pattern
, the third case is applicable--the static compile
method is used solely for clarity. Constructing a pattern via new Pattern(..)
doesn't make sense from an explanatory point of view, because there's a sophisticated process which goes on to create a new Pattern
. To explain this process, the static method is named compile
, because the regex is essentially compiled to create the pattern.
In short, there is no programmatic purpose for making Pattern
only constructable via a static method.