What are the pros and cons of having static object creation methods over constructors?
class Foo {
private Foo(object arg) { }
public static Foo Create(object arg) {
if (!ValidateParam(arg)) { return null; }
return new Foo(arg);
}
}
Few that I can think of:
Pros:
- Return null instead of throwing an exception (name it
TryCreate). This can make code more terse and clean on the client side. Clients rarely expect a constructor to fail. - Create different kinds of objects with clear semantics, e.g.
CreatFromName(String name)andCreateFromCsvLine(String csvLine) - Can return a cached object if necessary, or a derived implementation.
Cons:
- Less discoverable, more difficult to skim code.
- Some patterns, like serialization or reflection are more difficult (e.g.
Activator<Foo>.CreateInstance())


Foo x = Foo.TryCreate(); if (x == null) { ... }). Handling a ctor exception is (Foo x; try { x = new Foo(); } catch (SomeException e) { ... }). When calling a normal method, I prefer exceptions to error codes, but with object creation,TryCreateseems cleaner. – dbkk Nov 16 '10 at 19:06