10 Jul 2008

Constructors are a bad idea

Effective Java begins by talking about the drawbacks of constructors: they do not have names to distinguish each other, they have to create an instance of the object (and not use a cached object), they have to create an instance of the class (and not a subclass or a proxy for remote calls, access control, etc). Instead of making programmers work around the deficiency of the language, it will be good if the language has no notion of constructors or a new operator; instead classes should have a static method named new (or something else if it's more appropriate for a particular class) that returns an object. Perhaps an allocate operator can be added (in place of new) that returns an unitialized object, and which can be invoked only from within the class.

So you have static factory methods as the default, with the flexibility they entail. And if you want full factory objects, as long as they have a new function with the same signature, it will be easier to retrofit them into an existing program. Moreover, if you have dynamic scope, it can get even better, because the factory instance doesn't have to get passed around everywhere.

No comments:

Post a Comment