Class design - properties or parameters?

I am developing a class ...

There are important methods that need the object passed to them, or they must be able to "get" the object.

So, the question is whether you should use getter / seters OR directly send the object as an argument to the method - for the method to work correctly. Or should you install objects through the constructor if they are really critical for the class to function properly?

+4
source share
4 answers

If it makes no sense to have an instance of this class without a specific object (for example, it makes no sense to create a data access class without connecting to the database), then this is a “dependency” and should be part of the constructor.

If your class can survive without it or use some default value, you could instead make it a property and check if it is assigned before use.

In most cases, I would strongly advocate constructor dependency injection.

+5
source

The question is not how “important” they are (each method should have the data it needs by definition). A better question is how often do they change. If they differ each time the method is called (or at least reasonably may be), they should be parameters. If they are expected to be usually the same for the life of the object (or a significant portion of it), they should be stored with the object.

In the latter case, do not just rely on the user calling setter. If required, they must be installed in the designer, even if they can be changed by the installer.

+5
source

As you mentioned, you have the following three options:

Use getters / setters

As you know, get / set will indicate the state of the object that is accessed several times (usually) during the lifetime of the object. Therefore, if you have a script like "CrucialMethod1" for "CrucialMethodN" consuming this state, then this can be used. In addition, it will also help expose the state from the outside.

Use as parameter for constructor

As a rule, the constructor parameter will “dictate” the state in which the object will be initialized. Therefore, if you have a scenario where "CrucialMethod" may or may not be called, this will not be most appropriate.

Use the method as a parameter

This would be useful in a scenario where "CrucialMethod" acts / transforms (depends) on the passed parameters. This makes it easier to call a method without depending on the state of the parameter.

Your call!

+3
source

If they are necessary for the class to function properly, you must require them in the constructor or install them inside it.

As for transferring it or not. I prefer when classes can take care of themselves so that he does the work and gets what she needs.

+1
source

All Articles