Is there a convention or correct order for chaining constructors?

96 views Asked by At

Ive been thinking about this and I've seen different examples on this. Usually I would chain constructors in a upward manner. So if I have 4 different constructors, starting with a default constructor, who calls the constructor where we need to pass in one argument, who calls the constructor where we need 2 arguments to pass in and so on, so we have usable objects, where all the fields hold data.

Is there a different approach to chaining constructor because I couldn't think of another case ? Why would I want my constructor, where I need 3 arguments to pass in, call my constructor where I only need to pass in 2 arguments ?

2

There are 2 answers

0
cameron1024 On

The Builder pattern works for this scenario. A rough demo could look like this:

Dog dog = new DogBuilder().setHeight(10).setWeight(40).setColor(Color.BROWN).build();

Each set method returns a reference to the DogBuilder instance, with that property set. Calling .build() calls a private/package private constructor with all values set.

This is a good article for reference: https://dzone.com/articles/design-patterns-the-builder-pattern

0
GhostCat On

I think "common sense" best practices are:

  • Minimize the number of constructors your class offers (for example by relying on the Builder pattern)
  • Yes, "upward chaining" where the n arg constructor calls an n+1 constructor (and provides a default argument) is probably the more common (and more useful) style.

But as the last sentence indicates: to a certain degree, this is about "personal" style. Or whatever "style" applies. When your team is used to do things in a different way, and you have hundreds of existing classes following that "special style", then you allow that "team internal" preference to guide your actions.