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() {
        this(DEFAULT_STATION, DEFAULT_CONDUCTOR);
    }

    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. :-)

2 comments:

Anonymous said...

My only objection to this style, which I explained in my weblog, is that if I browse your code, it's harder for me to find what your canonical constructor is, whereas a constant name such as init() makes it obvious.

Brian Oxley said...

Steve, I agree with Cedric's goal of clarity, but I commented on his article that I can achieve clarity by placing the single privileged constructor first and all the others following (reverse of the order presented in my example). Giving the constructor a special name like "init" doesn't seem particularly clarifying to me, but I recognize that this point is one more of taste than a technical one.