javaconstructorthis

Is it good or bad to delegate to another constructor (using this()) within a constructor


Oracle reference doesn't tell about best practice of this keyword while we overload constructors. Can anyone suggest the best practice for it?

Option 1: delegate to another constructor

public class A {
    private int x, y, z, p;  

    public A() {
        this(1,1,1,1);
    }

    public A(int x, int y, int z, int p) {
        this.x = x;
        this.y = y;
        this.z = z;
        this.p = p;
    }
}

and

Option 2: set each field rather than delegating

public class A {
    private int x, y, z, p;  

    public A() {
        this.x = 1;
        this.y = 1;
        this.z = 1;
        this.p = 1;
    }

    public A(int x, int y, int z, int p) {
        this.x = x;
        this.y = y;
        this.z = z;
        this.p = p;
    }
}

Solution

  • The first one is the best.

    It is referenced multiple times in the offical docs and in many books. It is a specific case of method-chaining or, as others noted in the comments, telescoping constructors. They allows you to write less code and to not repeat yourself (DRY).

    You can find that approach everywhere in solid libraries like Apache Commons and also in the best practices of other platforms. Finally, the famous book Thinking in Java, use this form in the Initialization & Cleanup chapter (Calling constructors from constructors section).