Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor Chain

Why do we use this form? (it's on a course on plural sight for Java)

public MathEquation(char opCode)
    {
        this.opCode = opCode;
    }

public MathEquation(char opCode , double leftVal , double rightVal)
    {
        this(opCode);
        this.leftVal = leftVal;
        this.rightVal = rightVal;
    }

and why not this?

public MathEquation(char opCode , double leftVal , double rightVal)
    {
        this.opCode = opCode
        this.leftVal = leftVal;
        this.rightVal = rightVal;    
    }
like image 699
ShaDiliX Avatar asked Jul 29 '26 13:07

ShaDiliX


2 Answers

Because if, for some reason, you need to do something more with the opCode (like turning it to uppercase before storing it, or check it's in some range, or anything like that), you won't have to repeat that code in the two constructors. One will simply invoke the code already written in the other.

This general principle is called DRY: Don't Repeat Yourself.

Note that it's often being made in the other direction: the simplest constructor calls the most complex one, specifying what default values to pass for the missing arguments:

public MathEquation(char opCode) {
    this(opCode, 0.0, 0.0);
}
like image 114
JB Nizet Avatar answered Jul 31 '26 01:07

JB Nizet


The point is: you want to minimize the amount of different work that constructors do.

And from that point of view the optimal solution would be that the one arg constructor invokes the 3 arg constructor (making it also explicit what default values should be used for the other two arguments)! When you do that only one constructor does something - whereas in your example the 3 arg constructor does something and calls the other one.

Meaning: neither of the forms used in the question are ideal.

like image 44
GhostCat Avatar answered Jul 31 '26 03:07

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!