Sunday, November 07, 2004

Why chaining constructors is good

Cedric writes why chaining construtors is bad. Actually, what he advocates is concentrating all the construction logic in a single method (e.g., init), and turning constructors into forwarders to this privileged method.

But he does not mention that this is no different from having a single privileged constructor and chaining all other constructors to that. Hence:

class ChooChoo {
    public static final Station DEFAULT_STATION = new Station();
    public static final Conductor DEFAULT_CONDUCTOR = new Conductor();

    private final Station home;
    private final Conductor chief;

    public ChooChoo() {

    public ChooChoo(final Station home) {
        this(home, DEFAULT_CONDUCTOR);

    public ChooChoo(final Conductor chief) {
        this(DEFAULT_STATION, chief);

    public ChooChoo(final Station home, final Conductor chief) {
        this.home = home;
        this.chief = chief;

In my code, init is a privileged constructor (sometimes a private one) which I find more clear. But Cedric mentions that init increases clarity for him. We should pair together. :-)

Post a Comment