Overloading a constructor
(Another snippet I originally posted to CodeKeep.)
Using ‘this’ can make your code simpler and easier to read.
Here is a hard way to create a pair of constructors:
public class ClassHardWay
{
private int _id;
private string _name;
public ClassHardWay(string name)
{
_id = 1;
_name = name;
}
public ClassHardWay(int id, string name)
{
_id = id;
_name = name;
}
}
Here’s an easier way:
public class ClassEasyWay
{
private int _id;
private string _name;
public ClassEasyWay(string name) : this (1,name)
{
}
public ClassEasyWay(int id, string name)
{
_id = id;
_name = name;
}
}
So why is the second way better than the first?
- There is less code. Fewer lines == fewer mistakes.
- What if you want to add another property/field? Are you going to create a third constructor and set all of the field again? What about a situation where your input list grows to 5 or 8 input arguments. Recycling working code is better than re-writing it over and over again. Think about an address class that starts with a very simple, street, city, state then grows to street1, street2, city, state, country, postal code. Do you want to keep adding new constructors or would you rather extend the ones you already have?
- It’s easier to test. Once you’ve tested the simplest constructor, every other test can focus on testing what’s different in the growing constructor list as opposed to retesting every single input argument. Now maybe, that’s kind of a cop out because you should be testing all of your input args (as in black box style testing). I disagree. Test the new stuff as your test grow. Build solid tests for what you have today, then continue that effort as your code base grows.
- In the end, it is a choice.
- I can write one line and reuse it 15 times. I’d always rather do that than write the same line over and over again, more 15 times. Each time I risk making a mistake.
