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.
new Pattern(".")
is as readable if not more so, isn't it :) – Cecillacompile
may potentially have a mechanism to decide which constructor to use depending on the actual input provided that multiple constructors are available. Feel free to list it as an answer and I'll vote for it :) – CecillaPattern.compile(str)
andPattern.compileFromJson(str)
andPattern.compileFromXML(str)
. – Historiography