Static factory methods vs Instance (normal) constructors?
Solution 1:
In Effective Java, 2nd edition, Joshua Bloch certainly recommends the former. There are a few reasons I can remember, and doubtless some I can't:
- You can give the method a meaningful name. If you've got two ways of constructing an instance both of which take an int, but have different meanings for that int, using a normal method makes the calling code much more readable.
- A corollary of the first - you can have different factory methods with the same parameter list
- You can return null for "potentially expected failure" cases whereas a constructor will always either return a value or throw an exception
- You can return a type other than the declared (e.g. return a derived class)
- You can use it as a factory, to potentially return a reference to the same object several times
The downsides:
- It's not as idiomatic, currently - developers are more used to seeing "new"
- If you see "new" you know you're getting a new instance (modulo the oddity I mentioned recently)
- You need to make appropriate constructors available for subclasses
- In C# 3, constructor calls are able to set fields/properties in a compact manner with object initializer expressions; the feature doesn't apply to static method calls
Solution 2:
I write a constructor when creating the instance has no side effects, i.e. when the only thing the constructor is doing is initializing properties. I write a static method (and make the constructor private) if creating the instance does something that you wouldn't ordinarily expect a constructor to do.
For example:
public class Foo
{
private Foo() { }
private static List<Foo> FooList = new List<Foo>();
public static Foo CreateFoo()
{
Foo f = new Foo();
FooList.Add(f);
return f;
}
}
Because I adhere to this convention, if I see
Foo f = Foo.CreateFoo();
Bar b = new Bar();
while reading my code, I have a very different set of expectations about what each of those two lines is doing. That code isn't telling me what it is that makes creating a Foo different from creating a Bar, but it's telling me that I need to look.
Solution 3:
I've been working on a public API recently, and I've been agonizing over the choice of static factory methods versus constructor. Static factory methods definitely make sense in some instances, but in others it's not so clear and I'm uncertain whether consistency with the rest of the API is reason enough to include them over constructors.
Anyway, I came across a quote from a Bill-Venners interview with Josh Bloch that I found helpful:
When you are writing a class, you can run down the my book's list of the advantages of static factories over public constructors. If you find that a significant number of those advantages actually apply in your case, then you should go with the static factories. Otherwise you should go with the constructors.
Some people were disappointed to find that advice in my book. They read it and said, "You've argued so strongly for public static factories that we should just use them by default." I think the only real disadvantage in doing so is that it's a bit disconcerting to people who are used to using constructors to create their objects. And I suppose it provides a little less of a visual cue in the program. (You don't see the new keyword.) Also it's a little more difficult to find static factories in the documentation, because Javadoc groups all the constructors together. But I would say that everyone should consider static factories all the time, and use them when they are appropriate.
Having read that quote, and the study that Uri mentioned*, I'm feeling inclined to err in favour of constructors unless there are compelling reasons to do otherwise. I think a static factory method without good cause is probably just unnecessary complexity and over-engineering. Though I might well change my mind again by tomorrow...
*Unfortunately this study focused less on static factory methods and more on the factory pattern (where a separate factory object exists to create new instances), so I'm not sure one can really draw the conclusion that static factory methods confuse many programmers. Although the study did give me the impression that they often would.
Solution 4:
If your object is immutable, you may be able to use the static method to return cached objects and save yourself the memory allocation and processing.
Solution 5:
There's a paper from ICSE'07 that studied the usability of constructors vs. factory patterns. While I prefer factory patterns, the study showed that developers were slower in finding the correct factory method.
http://www.cs.cmu.edu/~NatProg/papers/Ellis2007FactoryUsability.pdf