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,TryCreate
seems cleaner.Name
andCsvLine
types, rather than express requirements via method names. This would allow you to overload Create. Using strings for both could be considered to be "primitive obsession" (assuming you've not made this choice for known performance reasons). Check out Object Calisthenics for a fun way to explore this.