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[]
:
string.fromcharacters(chars);
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
Post a Comment