Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 324
Vidar Avatar asked Mar 10 '09 22:03

Vidar


2 Answers

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.

like image 199
Matt Hamilton Avatar answered Oct 03 '22 23:10

Matt Hamilton


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.

like image 28
MarkusQ Avatar answered Oct 03 '22 22:10

MarkusQ