Search |
||
Are constructors the enemy?Posted by timboudreau on March 31, 2009 at 6:47 PM PDT
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
»
Related Topics >>
J2SE Comments
Comments are listed in date ascending order (oldest first)
Submitted by arittner on Tue, 2009-03-31 23:58.
This is a good sample of a pitfall:
public class Super {
String value;
// This class implements PropertyChangeSupport.
setValue (String value) {
firePropertyChange ("value", getValue(), this.value = value);
}
getValue () {
return value;
}
}
public class Sub extends Super {
TimeZone tz = getCurrentTimeZone();
Sub () {
super();
prepareListener(); // Create PropertyChangeListener.
setValue ("Hello World: My Timezone is: ");
}
public propertyChange (PropertyChangeEvent pce) {
if ( "value".equals (pce.getPropertyName() ) ) {
System.out.println (getValue() + tz);
}
}
}
On propertyChange of "value" the TimeZone is null.
This simple example is typical for big Java Beans with chaining Property Change Events. But IMHO you'll fall in the same trap with factories.
Best regards,
josh.
Submitted by giorgio42 on Wed, 2009-04-01 04:54.
We all know that we must not call methods in a constructor body, which can be overridden.
Why this should make constructors a bad thing per se? After all somehow somewhere the objects have to be constructed.
Why not stop overestimating ourselves by thinking we are able to outsmart geniuses like Gilead Bracha or Joshua Bloch (or, looking at a different language, Bjarne Stroustrup) with a quick blog entry.
Submitted by grabity on Wed, 2009-04-01 06:55.
Even Josh Bloch agreed that he shouldn't have used constructors for the java collections library.
Submitted by timboudreau on Wed, 2009-04-01 08:49.
> This is a good sample fo a pitfall:
Indeed, I've fixed a lot of such bugs.
Submitted by i30817 on Wed, 2009-04-01 18:22.
Disable calling public and protected functions in constructors.
Problem solved?
Submitted by pepijnve on Thu, 2009-04-02 12:18.
What's being suggested reminds me of ObjectiveC where you always have distinct allocation and initialization of objects. In a way ObjectiveC style init* methods are exactly the factory methods that you're suggesting which at least gives a precedent of this pattern being used in a real language.
|
||
|
|