Are constructors the enemy?
My friend Jon writes an interesting blog on the problem of constructors, and how a language might improve on them - and comes to a fairly startling solution.
The major problems with constructors as I see it are
- Especially in deep inheritance hierarchies, or when you inherit from a class in a library which could involve incompatibly, it is easy for your object to be called when it is in a not-fully-initialized state. We just had to do an update release, NetBeans 6.5 to deal with such a change in JDK 1.6_12 - this conversation shows the tip of the iceberg that crashed into NetBeans when changes from JDK 7 were backported - because of such a problem
- A constructor ties you to the precise type of the object being constructed. As a library author, you get much more flexibility with a factory method, where you can return a subclass, possibly choosing which one based on an argument to the factory method. This makes it much easier to keep backward compatibility and guarantees your object is never exposed in a semi-initialized state (unless you're inheriting from something you don't control, which should be avoided when possible
Jon takes the exact opposite approach in his blog, suggesting running toward the problem - make semi-initialized objects the common case while eliminating constructors.I don't know how realistic that would be for a language, but it is some interesting food for thought!