简体   繁体   中英

Should optional parameters be listed in a constructor signature?

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!

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).

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM