Note that there are some explanatory texts on larger screens.

plurals
  1. POHow many variables should a constructor have?
    text
    copied!<p>I realize this is a pretty open question and could get a variety of answers, but here goes.</p> <p>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. </p> <p>In an effort to encapsulate the data of a class, I declare the members private, initialize them in my constructor, and use public accessors.</p> <p>Here is an example:</p> <pre><code>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 } </code></pre> <p>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. </p> <p>Is this considered bad programming practice? Is there a general limit to the number of variables you should pass into a constructor?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload