Search code examples
c#class-design

Class Design - Properties or Parameters?


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?


Solution

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