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?
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.
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.
you could consolidate the parameters into a Parameter Object and just pass that instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With