Tuesday, January 22, 2019 ..:: Home ::.. Register  Login
All blog entries are the opinions of the author and do not necessarily reflect the opinions of their employer. All the code presented is for explanation and demonstration purposes only. Any damages incurred to your site and/or data are not the responsibility of the author. Every effort is taken to ensure the code properly compiles, however sometimes there are some hiccups and you might be required to do your own debugging.
   TechTidBits (Blog)  

Series: Coding Contentions: Constructor Chaining, do you go up or down?

Aug 27

Written by:
Wednesday, August 27, 2008 8:54 PM  RssIcon

If you are reading this blog, hopefully you're into C# and therefore OOP.  I would hope you've heard of constructors, but have you heard of Constructor Chaining?  It's the process of keeping your code DRY by having one constructor method calling another.  There are two ways to do it, general to specific (forward, down) or the other way around, specific to general (backwards, up the object hierarchy tree).  Both have their benefits and draw backs. 

Slang for this is daisy chaining your constructors.

When you write your constructors, do you write the same code in each?  If you have each constructor calling some type of DatabaseInit() method, maybe you should be looking at Constructor Chaining.  At the minimal expense of a few additional method calls, you can easily keep your code dry and dramatically reduce your maintenance time and debugging efforts as well!  This a fantastic way to keep your code DRY as well.

The concept is identical to daisy chaining your constructors.  But there are two ways to do this, going "forwards/down" or "backwards/up."  By direction, I mean, are you calling methods more generic or less generic?  Are you calling the next constructor with more parameters or less. 

I will illustrate with an example using a Vehicle analogy.  The Vehicle class is simplistic for demonstration purposes.  It has a modelName, ManufacturedYear and a vin.  Later we'll be adding a vin to see the comlicated with each approach.

Vehicle Class

This class is using the backwards direction of daisy chaining the constructors.  The basic concept is going from specific method with populated parameters to more generic methods also with properly populated parameters.  Taking this example to the next level, we'll look at calling the base constructors directly.

Car Class

As you can see, there is nothing wrong with calling the base constructors directly.  In this case, each of the constructors is calling a Car constructor with properly populated parameters.  Next we will look at schmooshing (yup, that's the technical term :>) these two techniques together

Motorcycle Class

Again, we're going backwards, from specific to more generic.  In other words, we're walking our way backwards through the object structure.  If you think this is mirroring the object hierarchy tree, you're correct, that's the point!

Ok, so what's the alternative?  Instead of going backwards, you could go forwards.  HUH?  You say, how can you go forward if you don't have those parameters populated with values yet?  Simple, you use default, dummy values.  Let me illustrate with a Truck class.

Truck Class

From this Truck class you can see the method calls are going from the generic to the more specific and using defaults/nulls/zeros in places where you/the developer does not know what the values are yet.

Now that you've seen both ways to implement Constructur Chaining, how is a juniro or an intermediate developer to decide on which way to use?  Ok, so your boss tells you which way to go, but is it cause they don't have to test/debug/maintain that code later on after it's released?  Let's use a real life example here to see which one you prefer.  Let's add one field to the Vehicle class, a VIN and let's see which way is easier to code and maintain for you.

Backwards Chaining

  • add the string field to the Vehicle class
  • copy the last constructor for it's method declaration (you could type it out but cut'n'pasting is our friend :>), you want to take the most specific constructor for this purpose
  • paste it into the code, add in the ", string vin" to the end of the parameter list, move the availableOptions from the method body to the constructor chaining method and then add in the " = vin;"

Vechicle Class With Vin Constructors

That's it!  You've effectively added the vin field and updated the constructors without duplicating any code, and all the proper fields will be set properly.  Let's try pushing this new vin field down to the sub classes.  Because of the way the Car class is created it'll be easier to update.

  • copy'n'paste the most specific/widest constructor (the one with carName, yearMade and availableOptions) including the braces {} for it's declaration then add in the ", string vin" and you're done!

Car Class with Vin

Let's try again with the Motorcycle class.

  • it's basically samething as the Car class with the added work of setting the vin field in the constructor.

Motorcycle Class with Vin


Forward Chaining

We're going to update the Truckk class to illustrate going fowards.

  • since we're adding something to the end of the chain (we're adding a new more specific parameter list, so we're going to be the new end point for the constructors), we have to push that end point out, start with the last constructor, the most specific one since it has most of the business logic implemented
  • cut'n'paste that constructor (signature, method body, everything) and paste it right after
  • add the ", string vin" to the end of that constructor parameter list
  • add the field setter in the construtor body (have to set the protected string variable somehow right?)
  • but now that we've changed that constructor, you're no longer DRY, you still have the old setters in the other constructor you cut'n'paste from, so you'll need to change that constructor to call the new one you just added
  • delete that constroctur's method body
  • add the constructor chain to the new method you just added

Truck Class with Vin



I much prefer going up/backwards when I'm daisy chaining my constructors.  Why?  Cause you always have populated values.  You're also always guaranteed to run each method in the chain so you're always ensured proper object initialization.  Therefore debugging and maintenance issues are minimized (read that as "cheaper" :>).

When you go forwards, you're always having to push out the constructors for each new field you add to the constructor.  AND there's no guaranteed you're not going to forget something (that's happened in my last job and caused all kinds of hard to find bugs :<).  People will get lazy or just forget to push out those constructors and that's when your code stops being DRY and things get missed.

References: Code Sample

The Code Project: An Intro to Constructors in C#

MSDN: Proper constructor chaining direction (dialog with Peter Ritchie, MVP, ex of going up/backwards)

C#411: Constructor Chaining

Industrial Logic: Chain Constructors (ex of going down/forwards)


Location: Blogs Parent Separator TechTidBits

3 comment(s) so far...

Re: Series: Coding Contentions: Constructor Chaining, do you go up or down?


Allow me one question please:

- Once a Truck object is created, I feel there's a need for a method like this: Initialize(modelName,yearMade, availableOptions)

Truck t = new Truck("model1", 2001, new List);

t.Initialize("model2", 2002, new List...);
t.Initialize("model3", 2003, new List...);
t.Initialize("model4", 2004, new List...);


How would you write the Initialize method in order to avoid copy paste code from the constructor ??

public Initialize( string modelName, int yearMade, List availableOptions )
this.modelName = modelName;
this.yearName = yearName;
this.availableOptions = availableOptions;

If I do this, all the benefit of having the initialization code in one place, vanishes.

By Charlex Rex on   Thursday, April 23, 2009 8:54 AM

Re: Series: Coding Contentions: Constructor Chaining, do you go up or down?

Hey Charlex, thanks for the question, that's a good one!

I believe in keeping things DRY (Don't Repeat Yourself) and sometimes that means refactoring things out of constructors into your own methods. Nothing wrong with it, especially since you have the F12 in Visual Studio to follow the method chain. :>

To answer your question, you would actually refactor that constructor into another method (Initialize in your example,that's cool) which would return a Truck object, or you could leave the constructor declaration and create a new Initialize method with the same signature (don't forget to return a Truck object).

There's a slightly modified version of this in the Factory Design Pattern. It's slightly different from the above example, but I think you'll be able to see its merits pretty quickly once you poke around with it.

MDSN: Exploring the Factory Design Pattern (

By phenry on   Thursday, April 23, 2009 9:10 AM

Re: Series: Coding Contentions: Constructor Chaining, do you go up or down?

Thanks Suresh. But lately I've been thinking about this and it appears like more and more people are doing just the two constructor bit. One empty constructor to satisfy Blend/VS/MVVM/XAML and one that takes everything and the kitchen sink. I'm still learning more and more! How about you? What do you like/prefer/use?

By Peter Henry on   Tuesday, May 15, 2012 8:14 AM

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Add Comment   Cancel 
Copyright 1999-2012 by   Terms Of Use  Privacy Statement