A quick question about constructor style:
Which do you prefer, independently built constructors or nested
constructors?
eg.
// Eclipse automatically generated style
AClass() {
}
AClass(String str) {
this.str = str;
}
AClass(String str, int num) {
this.str = str;
this.num = num;
}
or
// "Elements of Java Style" recommended style
AClass(String str, int num) {
this.string = string;
this.num = num;
}
AClass(String str) {
this(str, DEFAULT_NUM);
}
AClass() {
this("", DEFAULT_NUM);
}
Domagoj Klepac - 15 May 2006 15:05 GMT
>A quick question about constructor style:
>Which do you prefer, independently built constructors or nested
>constructors?
It really depends on the amount of logic in the constructors, but, as
a general preference, nested constructors - no code duplication.
Domchi

Signature
Ouroboros ltd. - http://www.ouroboros.hr
Antispam: to reply, remove extra monkey from reply-to address.
Jeffrey Schwab - 15 May 2006 15:12 GMT
>> A quick question about constructor style:
>> Which do you prefer, independently built constructors or nested
>> constructors?
>
> It really depends on the amount of logic in the constructors, but, as
> a general preference, nested constructors - no code duplication.
Ditto.
Duane Evenson - 15 May 2006 15:25 GMT
>>> A quick question about constructor style:
>>> Which do you prefer, independently built constructors or nested
[quoted text clipped - 4 lines]
>
> Ditto.
thanks
Robert Klemme - 15 May 2006 15:26 GMT
>>> A quick question about constructor style:
>>> Which do you prefer, independently built constructors or nested
[quoted text clipped - 4 lines]
>
> Ditto.
+1
robert
Tobias Schröer - 15 May 2006 15:21 GMT
Duane Evenson schrieb:
> A quick question about constructor style:
> Which do you prefer, independently built constructors or nested
[quoted text clipped - 24 lines]
> this("", DEFAULT_NUM);
> }
I'd prefer the latter one. Every constructor finally leads to the "most
flexible" one. If you have to change anything, you have to do it only
once and not - as in this example - thrice.
It's the same with methods: normally you would implement
List#add(Object) as
<code>
public void add(Object obj) {
this.add(this.size(), obj);
}
</code>
and not do the implementation twice for List#add(Object) and
List#add(int, Object), which are technically the same.
Tobi