views:

178

answers:

4

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?

+3  A: 

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.

Matt Hamilton
A: 

If they are required to the class operating correctly you should require them in the constructor or set them inside it.

As for passing it in or not. I prefer when classes can take care of themselves so have it do the work and get what it needs.

Andrew Clark
+3  A: 

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.

MarkusQ
+2  A: 

As you mentioned, you have the following three options:

Use getters/setters

As you might know, get/set will indicate a state of the object, that is accessed multiple times(generally) during the object lifetime. So if you have a scenario like 'CrucialMethod1' to 'CrucialMethodN' consuming this state then this could be used. Additionally, this will also help in exposing the state externally.

Use as parameter to constructor

Generally, a parameter to the constructor will 'dictate' the state into which the object will be initialized. So if you have a scenario where the 'CrucialMethod' may or may not be called, then this would not be most appropriate.

Use as parameter to the method

This would be useful in the scenario when the 'CrucialMethod' acts/transforms(depends) on the parameters passed. This facilitates calling the method without dependency on the state of the parameter being.

Your call!

Codex