constructor style?

D

Duane Evenson

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);
}
 
D

Domagoj Klepac

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
 
J

Jeffrey Schwab

Domagoj said:
It really depends on the amount of logic in the constructors, but, as
a general preference, nested constructors - no code duplication.

Ditto.
 
?

=?ISO-8859-1?Q?Tobias_Schr=F6er?=

Duane said:
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);
}

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top