3

I'm trying to understand constructor chaining better. I understand that this technique can be used to reduce code duplication for initialization of a class object and I also understand the order in which they're executed.

I found the following example and I cannot see clearly what the benefits are in the code? And whether it's necessary? I don't understand why both constructors have 'this' keyword in them, would calling either constructor (and passing in relevant parameters) have the same result?

//Constructors
public MyClass(double distance, double angle) : this(distance, angle, 0) 
{
}

public MyClass(double distance, double angle, double altitude) : this()
{
Distance = distance;
Angle = angle;
Altitude = altitude;
}
  • Your code wouldn't compile, unless MyClass was actually a struct. – svick Jun 4 '13 at 12:57
3

First off, you get reduced code duplication as the top constructor is chained to the second - passing in a 0 for the altitude parameter; the other passed in parameters are passed in to the chained constructor from the values used in the constructor itself (the distance and angle parameters). The reduced duplication is in the fact that the second constructor is the one doing the initialization and it is not duplicated in the first constructor.

Another benefit is that you now have overloaded the constructor such that the altitude parameter is optional and will default to 0 if not supplied.

The second constructor is chained to a parameterless constructor that you have not shown in your example. This one may very well initialized other parts of the class - initialization that is not repeated elsewhere.


would calling either constructor (and passing in relevant parameters) have the same result?

Sure. But this is some nice syntactic sugar - makes the code easy to read and short.

0

In my opinion the most relevant benefit apart from achieving minimal code duplication is that using an object with chained constructors always yields full and correctly initialized objects with the least amount of executed code, even if the client doesn't have enough information about the parameter values.

Another point is that by using chained constructors, you are able to get more construction possibilities for free if you use them in Telescopic Constructor Pattern. If you find yourself confused with too many parameters, consider the Builder Pattern instead. Joshua Bloch wrote about the refactoring in Effective Java Item 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.