I realize this is a pretty open question and could get a variety of answers, but here goes.
Using C# (or Java, or any OO language), is there a general rule that states how many variables should be passed into the constructor? The number of variables I am passing into the constructor of the extended classes seem to be getting out of hand.
In an effort to encapsulate the data of a class, I declare the members private, initialize them in my constructor, and use public accessors.
Here is an example:
public class A
{
private int var1;
private int var2;
private int var3;
//3 variables passed in
public A(int v1, int v2, int v3)
{
var1 = v1;
var2 = v2;
var3 = v3;
}
//Properties (accessors) here
}
public class B : A
{
private int var4;
private int var5;
//5 variables passed in
public B(int v1, int v2, int v3, int v4, int v5)
: base(v1,v2,v3)
{
var4 = v4;
var5 = v5;
}
//Properties (accessors) here
}
public class C : B
{
private int var6;
private int var7;
//7 variables passed in !!!
public C(int v1, int v2, int v3, int v4, int v5, int v6, int v7)
: base(v1,v2,v3,v4,v5)
{
var6 = v6;
var7 = v7;
}
//Properties (accessors) here
}
My constructors are usually passing in different objects, not just ints. I started questioning my design when I started passing in 7 variables to the constructor of the child class, but I have also had trouble figuring out a different way to do this.
Is this considered bad programming practice? Is there a general limit to the number of variables you should pass into a constructor?
Generally I've found if there's more than 3, that's a sign to do a quick sanity check on the design. If there's more than 5, that's a major warning that something is probably wrong with the design.
However, note the word "probably" - in the end, the only real rule is use as many as needed to function, no more and no less. There are always exceptions and cases where more parameters makes the most sense.
If the parameters are related somehow, you should encapsulate them into a container class.
If the parameters are not related - e.g. it makes no sense to group them into a container class - your class is probably doing too many things. There's generally no reason a single class should be aware of 7 totally disparate pieces of information. Break your class apart into separate classes. It might make sense to delegate parameters 3 and 4 to a subclass and 5, 6 and 7 to another class for example - and your parent class simply coordinates the operations between them.