<p>Let's say you have a class called Customer, which contains the following fields:</p>

<ul>
<li>UserName</li>
<li>Email</li>
<li>First Name</li>
<li>Last Name</li>
</ul>

<p>Let's also say that according to your business logic, all Customer objects must have these four properties defined.</p>

<p>Now, we can do this pretty easily by forcing the constructor to specify each of these properties.  But it's pretty easy to see how this can spiral out of control when you are forced to add more required fields to the Customer object.  </p>

<p>I've seen classes that take in 20+ arguments into their constructor and it's just a pain to use them.  But, alternatively, if you don't require these fields you run into the risk of having undefined information, or worse, object referencing errors if you rely on the calling code to specify these properties.</p>

<p>Are there any alternatives to this or do you you just have to decide whether X amount of constructor arguments is too many for you to live with?</p>

[{'answer_id': 40276, 'author': 'Aldie', 'author_id': 4133, 'author_profile': 'https://Stackoverflow.com/users/4133', 'pm_score': -1, 'selected': False, 'text': "<p>Unless it's more than 1 argument, I always use arrays or objects as constructor parameters and rely on error checking to make sure the required parameters are there.</p>\n"}, {'answer_id': 40278, 'author': 'McKenzieG1', 'author_id': 3776, 'author_profile': 'https://Stackoverflow.com/users/3776', 'pm_score': 3, 'selected': False, 'text': '<p>If you have unpalatably many arguments, then just package them together into structs / POD classes, preferably declared as inner classes of the class you are constructing. That way you can still require the fields while making the code that calls the constructor reasonably readable.</p>\n'}, {'answer_id': 40284, 'author': 'Brian Warshaw', 'author_id': 1344, 'author_profile': 'https://Stackoverflow.com/users/1344', 'pm_score': 1, 'selected': False, 'text': "<p>Just use default arguments. In a language that supports default method arguments (PHP, for example), you could do this in the method signature:</p>\n\n<p><code>public function doSomethingWith($this = val1, $this = val2, $this = val3)</code></p>\n\n<p>There are other ways to create default values, such as in languages that support method overloading.</p>\n\n<p>Of course, you could also set default values when you declare the fields, if you deem it appropriate to do so.</p>\n\n<p>It really just comes down to whether or not it is appropriate for you to set these default values, or if your objects should be specced out at construction all the time. That's really a decision that only you can make.</p>\n"}, {'answer_id': 40287, 'author': 'Adam Hollidge', 'author_id': 4069, 'author_profile': 'https://Stackoverflow.com/users/4069', 'pm_score': 2, 'selected': False, 'text': '<p>Style counts for a lot, and it seems to me that if there is a constructor with 20+ arguments, then the design should be altered. Provide reasonable defaults.</p>\n'}, {'answer_id': 40288, 'author': 'Ethan Gunderson', 'author_id': 2066, 'author_profile': 'https://Stackoverflow.com/users/2066', 'pm_score': 3, 'selected': False, 'text': "<p>I think it all depends on the situation.  For something like your example, a customer class, I wouldn't risk the chance of having that data being undefined when needed.  On the flip side, passing a struct would clear up the argument list, but you would still have a lot of things to define in the struct.  </p>\n"}, {'answer_id': 40289, 'author': 'helloandre', 'author_id': 50, 'author_profile': 'https://Stackoverflow.com/users/50', 'pm_score': 2, 'selected': False, 'text': '<p>I would think the easiest way would be to find an acceptable default for each value. In this case, each field looks like it would be required to construct, so possibly overload the function call so that if something is not defined in the call, to set it to a default.</p>\n\n<p>Then, make getter and setter functions for each property so that the default values could be changed.</p>\n\n<p>Java implementation:</p>\n\n<pre><code>public static void setEmail(String newEmail){\n    this.email = newEmail;\n}\n\npublic static String getEmail(){\n    return this.email;\n}\n</code></pre>\n\n<p>This is also good practice to keep your global variables secure.</p>\n'}, {'answer_id': 40292, 'author': 'Booji Boy', 'author_id': 1433, 'author_profile': 'https://Stackoverflow.com/users/1433', 'pm_score': 2, 'selected': False, 'text': "<p>Steve Mcconnell writes in Code Complete that people have trouble keeping more 7 things in their head at a time, so that'd be the number I try to stay under.  </p>\n"}, {'answer_id': 40298, 'author': 'spoulson', 'author_id': 3347, 'author_profile': 'https://Stackoverflow.com/users/3347', 'pm_score': 1, 'selected': False, 'text': '<p>I agree on the 7 item limit Boojiboy mentions.  Beyond that, it may be worth looking at anonymous (or specialized) types, IDictionary, or indirection via primary key to another data source.</p>\n'}, {'answer_id': 40299, 'author': 'OwenP', 'author_id': 2547, 'author_profile': 'https://Stackoverflow.com/users/2547', 'pm_score': 3, 'selected': False, 'text': '<p>I think the "pure OOP" answer is that if operations on the class are invalid when certain members aren\'t initialized, then these members must be set by the constructor.  There\'s always the case where default values can be used, but I\'ll assume we\'re not considering that case.  This is a good approach when the API is fixed, because changing the single allowable constructor after the API goes public will be a nightmare for you and all users of your code.</p>\n\n<p>In C#, what I understand about the design guidelines is that this isn\'t necessarily the only way to handle the situation.  Particularly with WPF objects, you\'ll find that .NET classes tend to favor parameterless constructors and will throw exceptions if the data has not been initialized to a desirable state before calling the method.  This is probably mainly specific to component-based design though; I can\'t come up with a concrete example of a .NET class that behaves in this manner.  In your case, it\'d definitely cause an increased burden on testing to ensure that the class is never saved to the data store unless the properties have been validated.  Honestly because of this I\'d prefer the "constructor sets the required properties" approach if your API is either set in stone or not public.</p>\n\n<p>The one thing I <em>am</em> certain of is that there are probably countless methodologies that can solve this problem, and each of them introduces its own set of problems.  The best thing to do is learn as many patterns as possible and pick the best one for the job.  (Isn\'t that such a cop-out of an answer?)</p>\n'}, {'answer_id': 40300, 'author': 'vitule', 'author_id': 1287, 'author_profile': 'https://Stackoverflow.com/users/1287', 'pm_score': 3, 'selected': False, 'text': '<p>I think your question is more about the design of your classes than about the number of arguments in the constructor. If I needed 20 pieces of data (arguments) to successfully initialize an object, I would probably consider breaking up the class.</p>\n'}, {'answer_id': 40324, 'author': 'toolkit', 'author_id': 3295, 'author_profile': 'https://Stackoverflow.com/users/3295', 'pm_score': 8, 'selected': True, 'text': '<p>Two design approaches to consider</p>\n\n<p>The <a href="http://www.hillside.net/plop/plop98/final_submissions/P10.pdf" rel="noreferrer">essence</a> pattern</p>\n\n<p>The <a href="https://martinfowler.com/bliki/FluentInterface.html" rel="noreferrer">fluent interface</a> pattern</p>\n\n<p>These are both similar in intent, in that we slowly build up an intermediate object, and then create our target object in a single step.</p>\n\n<p>An example of the fluent interface in action would be:</p>\n\n<pre class="lang-java prettyprint-override"><code>public class CustomerBuilder {\n    String surname;\n    String firstName;\n    String ssn;\n    public static CustomerBuilder customer() {\n        return new CustomerBuilder();\n    }\n    public CustomerBuilder withSurname(String surname) {\n        this.surname = surname; \n        return this; \n    }\n    public CustomerBuilder withFirstName(String firstName) {\n        this.firstName = firstName;\n        return this; \n    }\n    public CustomerBuilder withSsn(String ssn) {\n        this.ssn = ssn; \n        return this; \n    }\n    // client doesn\'t get to instantiate Customer directly\n    public Customer build() {\n        return new Customer(this);            \n    }\n}\n\npublic class Customer {\n    private final String firstName;\n    private final String surname;\n    private final String ssn;\n\n    Customer(CustomerBuilder builder) {\n        if (builder.firstName == null) throw new NullPointerException("firstName");\n        if (builder.surname == null) throw new NullPointerException("surname");\n        if (builder.ssn == null) throw new NullPointerException("ssn");\n        this.firstName = builder.firstName;\n        this.surname = builder.surname;\n        this.ssn = builder.ssn;\n    }\n\n    public String getFirstName() { return firstName;  }\n    public String getSurname() { return surname; }\n    public String getSsn() { return ssn; }    \n}\n</code></pre>\n\n<pre class="lang-java prettyprint-override"><code>import static com.acme.CustomerBuilder.customer;\n\npublic class Client {\n    public void doSomething() {\n        Customer customer = customer()\n            .withSurname("Smith")\n            .withFirstName("Fred")\n            .withSsn("123XS1")\n            .build();\n    }\n}\n</code></pre>\n'}, {'answer_id': 40364, 'author': 'Marcio Aguiar', 'author_id': 4213, 'author_profile': 'https://Stackoverflow.com/users/4213', 'pm_score': 4, 'selected': False, 'text': '<p>In your case, stick with the constructor. The information belongs in Customer and 4 fields are fine. </p>\n\n<p>In the case you have many required and optional fields the constructor is not the best solution. As @boojiboy said, it\'s hard to read and it\'s also hard to write client code.</p>\n\n<p>@contagious suggested using the default pattern and setters for optional attributs. That mandates that the fields are mutable, but that\'s a minor problem.</p>\n\n<p>Joshua Block on Effective Java 2 say that in this case you should consider a builder. An example taken from the book:</p>\n\n<pre><code> public class NutritionFacts {  \n   private final int servingSize;  \n   private final int servings;  \n   private final int calories;  \n   private final int fat;  \n   private final int sodium;  \n   private final int carbohydrate;  \n\n   public static class Builder {  \n     // required parameters  \n     private final int servingSize;  \n     private final int servings;  \n\n     // optional parameters  \n     private int calories         = 0;  \n     private int fat              = 0;  \n     private int carbohydrate     = 0;  \n     private int sodium           = 0;  \n\n     public Builder(int servingSize, int servings) {  \n      this.servingSize = servingSize;  \n       this.servings = servings;  \n    }  \n\n     public Builder calories(int val)  \n       { calories = val;       return this; }  \n     public Builder fat(int val)  \n       { fat = val;            return this; }  \n     public Builder carbohydrate(int val)  \n       { carbohydrate = val;   return this; }  \n     public Builder sodium(int val)  \n       { sodium = val;         return this; }  \n\n     public NutritionFacts build() {  \n       return new NutritionFacts(this);  \n     }  \n   }  \n\n   private NutritionFacts(Builder builder) {  \n     servingSize       = builder.servingSize;  \n     servings          = builder.servings;  \n     calories          = builder.calories;  \n     fat               = builder.fat;  \n     soduim            = builder.sodium;  \n     carbohydrate      = builder.carbohydrate;  \n   }  \n}  \n</code></pre>\n\n<p>And then use it like this:</p>\n\n<pre><code>NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).\n      calories(100).sodium(35).carbohydrate(27).build();\n</code></pre>\n\n<p>The example above was taken from <a href="https://rads.stackoverflow.com/amzn/click/com/0201310058" rel="noreferrer" rel="nofollow noreferrer">Effective Java 2</a></p>\n\n<p>And that doesn\'t only applies to constructor. Citing Kent Beck in <a href="https://rads.stackoverflow.com/amzn/click/com/0321413091" rel="noreferrer" rel="nofollow noreferrer">Implementation Patterns</a>:</p>\n\n<pre><code>setOuterBounds(x, y, width, height);\nsetInnerBounds(x + 2, y + 2, width - 4, height - 4);\n</code></pre>\n\n<p>Making the rectangle explicit as an object explains the code better:</p>\n\n<pre><code>setOuterBounds(bounds);\nsetInnerBounds(bounds.expand(-2));\n</code></pre>\n'}, {'answer_id': 40371, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 2, 'selected': False, 'text': '<p>I\'d encapsulate similar fields into an object of its own with its own construction/validation logic.</p>\n\n<p>Say for example, if you\'ve got</p>\n\n<ul>\n<li>BusinessPhone</li>\n<li>BusinessAddress</li>\n<li>HomePhone</li>\n<li>HomeAddress</li>\n</ul>\n\n<p>I\'d make a class that stores phone and address together with a tag specifying wether its a "home" or a "business" phone/address. And then reduce the 4 fields to merely an array.</p>\n\n<pre><code>ContactInfo cinfos = new ContactInfo[] {\n    new ContactInfo("home", "+123456789", "123 ABC Avenue"),\n    new ContactInfo("biz", "+987654321", "789 ZYX Avenue")\n};\n\nCustomer c = new Customer("john", "doe", cinfos);\n</code></pre>\n\n<p>That should make it look less like spaghetti.</p>\n\n<p>Surely if you have a lot of fields, there must be some pattern you can extract out that would make a nice unit of function of its own. And make for more readable code too.</p>\n\n<p>And the following is also possible solutions:</p>\n\n<ul>\n<li>Spread out the validation logic instead of storing it in a single class. Validate when user input them and then validate again at the database layer etc...</li>\n<li>Make a <code>CustomerFactory</code> class that would help me construct <code>Customer</code>s</li>\n<li>@marcio\'s solution is also interesting...</li>\n</ul>\n'}, {'answer_id': 15531632, 'author': 'Keith Pinson', 'author_id': 834176, 'author_profile': 'https://Stackoverflow.com/users/834176', 'pm_score': 5, 'selected': False, 'text': "<p>I see that some people are recommending seven as an upper limit. Apparently it is not true that people can hold seven things in their head at once; they can only remember four (Susan Weinschenk, <em>100 Things Every Designer Needs to Know about People</em>, 48). Even so, I consider four to be something of a high earth orbit. But that's because my thinking has been altered by Bob Martin.</p>\n\n<p>In <em>Clean Code</em>, Uncle Bob argues for three as an general upper limit for number of parameters. He makes the radical claim (40):</p>\n\n<blockquote>\n  <p>The ideal number of arguments for a function is zero (niladic). Next comes one (monadic) followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification&mdash;and then shouldn't be used anyway.</p>\n</blockquote>\n\n<p>He says this because of readability; but also because of testability:</p>\n\n<blockquote>\n  <p>Imagine the difficulty of writing all the test cases to ensure that all various combinations of arguments work properly.</p>\n</blockquote>\n\n<p>I encourage you to find a copy of his book and read his full discussion of function arguments (40-43).</p>\n\n<p>I agree with those who have mentioned the Single Responsibility Principle. It is hard for me to believe that a class that needs more than two or three values/objects without reasonable defaults really has only one responsibility, and would not be better off with another class extracted.</p>\n\n<p>Now, if you are injecting your dependencies through the constructor, Bob Martin's arguments about how easy it is to invoke the constructor do not so much apply (because usually then there is only one point in your application where you wire that up, or you even have a framework that does it for you). However, the Single Responsibility Principle is still relevant: once a class has four dependencies, I consider that a smell that it is doing a large amount of work.</p>\n\n<p>However, as with all things in computer science, there are doubtless valid cases for having a large number of constructor parameters. Don't contort your code to avoid using a large number of parameters; but if you do use a large number of parameters, stop and give it some thought, because it may mean your code is already contorted.</p>\n"}, {'answer_id': 58661084, 'author': 'rrswa', 'author_id': 3076593, 'author_profile': 'https://Stackoverflow.com/users/3076593', 'pm_score': 1, 'selected': False, 'text': '<p>In a more Object-Oriented situation of the problem, you can use properties in C#. It doesn\'t help much if you create an instance of an object, but suppose we have a parent class that needs too many parameters in its constructor.<br>\nSince you can have abstract properties, you can use this to your advantage. The parent class needs to define an abstract property that the child class must override.<br>\nNormally a class might look like:</p>\n\n<pre><code>class Customer {\n    private string name;\n    private int age;\n    private string email;\n\n    Customer(string name, int age, string email) {\n        this.name = name;\n        this.age = age;\n        this.email = email;\n    }\n}\n\nclass John : Customer {\n    John() : base("John", 20, "John@email.com") { \n\n    }\n}\n</code></pre>\n\n<p>It can become messy and unreadable with too many parameters.<br>\nWhereas this method:</p>\n\n<pre><code>class Customer {\n    protected abstract string name { get; }\n    protected abstract int age { get; }\n    protected abstract string email { get; }\n}\n\nclass John : Customer {\n    protected override string name =&gt; "John";\n    protected override int age =&gt; 20;\n    protected override string email=&gt; "John@email.com";\n}\n</code></pre>\n\n<p>Which is much cleaner code in my opinion and no contractors are needed in this case, which saves room for other necessary parameters.</p>\n'}]
['https://Stackoverflow.com/questions/40264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1574/']