Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to set lots of required properties than sending as parameters in a Constructor?

Tags:

c#

I have a class that in order to do it's job needs to have 8 different property values set. I want to make sure that all 8 properties are set before trying to execute a method. I currently have all the parameters passed in and set via the constructor. Is there a better way to do this?

like image 762
etoisarobot Avatar asked Apr 28 '10 15:04

etoisarobot


3 Answers

You can allow the object to be created without specifying values for all the properties and then the method would throw an InvalidOperationException if called before the object state is valid for the method call to execute, which in this case would mean that all 8 properties would have valid values.

This way you give more flexibility to the consumer. It can create a new instance at one moment, set it's properties at another and only then call the method. This is a "pattern" that is used through the .NET codebase and to which developers are already used.


Update:

This also simplifies things if you're adding other methods that don't need the full set of properties to be initialized. Yes we could add another constructor overload with the new set of properties, but what if we have 2 methods that both need one property of the same type to be initialized? This is not solvable by using constructor overloads.

like image 86
João Angelo Avatar answered Nov 08 '22 12:11

João Angelo


In my opinion if a class requires these 8 objects in order to function then they should be passed into the constructor and by no other means. I'm a big fan of dependency injection anyway, but this method also allows for better unit testing by passing in mocked objects and such.

like image 25
Antony Koch Avatar answered Nov 08 '22 14:11

Antony Koch


you could consolidate the parameters into a Parameter Object and just pass that instead.

like image 2
Sam Holder Avatar answered Nov 08 '22 14:11

Sam Holder