I am designing a class...
there are crucial methods that need an object passed to them or they need to be able to "get" an object.
So the question is, should you use getter/setters OR directly send the object as an argument to the method - in order for the method to work properly. Or should you set objects via the constructor if they are really crucial to the class operating correctly?
If it doesn't make sense to have an instance of this class without a certain object (eg it might make no sense to construct a data-access class without a connection to a database), then it's a "dependency" and should be part of the constructor.
If your class can survive without it, or can use some default value, then you could instead make it a property and check if it's assigned before being used.
I'd strongly advocate constructor dependency injection in most cases though.
The question isn't how "crucial" they are (every method needs to have the data it needs, by definition). A better question is how frequently do they change. If they'll be different each time the method is called (or at least reasonably could be) they should be parameters. If they are expected to generally be the same for the life of the object (or a significant fraction there of) they should be stored with the object.
In the latter case, don't just rely on the user calling a setter. If they are required, they should be set in the constructor even if they can be changed by a setter.
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