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?
This method has four parameters: the loan amount, the interest rate, the future value and the number of periods.
Example of parameterized constructor In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .
in short.. it's fine to not initialize your member variables in the constructor as long as you initialize them somewhere in the class before using them.. Save this answer.
For me, the correct answer is:
You should pass in as many variables as is required to setup the object in a state that is not invalid.
Anything else that is "option", I prefer to leave as properties, especially now that C# provides object initializers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With