design patterns - Static factory methods vs Instance (normal) constructors? -


in language both available, prefer see instance constructor or static method returns instance?

for example, if you're creating string char[]:

  1. string.fromcharacters(chars);

  2. new string(chars);

in effective java, 2nd edition, joshua bloch recommends former. there few reasons can remember, , doubtless can't:

  • you can give method meaningful name. if you've got 2 ways of constructing instance both of take int, have different meanings int, using normal method makes calling code more readable.
  • a corollary of first - can have different factory methods same parameter list
  • you can return null "potentially expected failure" cases whereas constructor always either return value or throw exception
  • you can return type other declared (e.g. return derived class)
  • you can use factory, potentially return reference same object several times

the downsides:

  • it's not idiomatic, - developers more used seeing "new"
  • if see "new" know you're getting new instance (modulo oddity mentioned recently)
  • you need make appropriate constructors available subclasses
  • in c# 3, constructor calls able set fields/properties in compact manner object initializer expressions; feature doesn't apply static method calls

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -