Reputation: 1303
With best practices in mind, what's the advisable approach to adding optional parameters to a constructor signature? Should you only ever list the core parameters and depend on initialisers for the non optional properties? Seems to me to be the most sensible approach!
Upvotes: 1
Views: 95
Reputation: 10455
Consider subclassing instead of several constructors.
Reason: Often two different different constructors indicate two different behaviors are desired. Different nehaviors should be implemented by different classes.
The subclass would then have both a name that indicates how it's a specialized version of the base class, and a constructor that ensures that this kind of object can only be created in a valid state.
Upvotes: 0
Reputation: 150108
In particular with the ability to assign property values with object initializers, multiple overloads for constructors are far less useful than they were. They were mostly useful in the past for setting mutable properties for code compactness.
Now one can write
MyClass my = new MyClass() { PropA = 1, PropB = 2 };
Almost as compact as
MyClass my = new MyClass(1, 2);
while being more expressive.
However, sometimes the nature of an object dictates that an overload would provide a meaningful contract to the object consumer. For example, providing an overload for a Rectangle class that accepts a length and a width is not unreasonable (I would not ding it on a code review). Personally I would still not provide an overload because object initializer syntax is more expressive, avoiding questions like "was that Rectangle(int length, int width) or Rectangle(int width, int length)?" while reading code (I know, intellisense helps while writing code).
Upvotes: 3
Reputation: 8564
As a rule of thumb, I add to a constructor only the parameters that are required to create a valid, working object. With the advent of object initializer syntax, it is much easier for the client to configure whatever other parameters he wants.
However, I think that this rule should have many exceptions: many times you might want to provide an overload that makes it easy and clearer to the developer what he can expect to be able to change about an object.
Upvotes: 1
Reputation: 41483
I believe this is a fine approach. Typically people use properties for optional parameters; but this makes the object mutable. Using optional constructor arguments/ctor overloads is a good approach to keep the object immutable.
Upvotes: 1