-3

from my class I include all dependencies in the constructor.

to decide which dependencies to pass what rules should I follow?

when I decide to use the parameters of a method instead of the constructor?.

Concrete example.

I have a service that perform a operation on DB. To do this it must have 3 class repositories that injected via constructor and two parameter l'object of the db and a structure of data input

class Foo(Repo1, Repo2, Repo3) 
{
   function doSomething(objectToDB, objectInputData);
} 

before posting I had put everything in the constructor. But then I had strong doubts and decided to ask

Is the question more complete? Thank you

3
  • 1
    Generally, you provide only the dependencies that your class and/or method requires to perform its function and no more... Commented Jul 29, 2018 at 22:30
  • 1
    I think the last sentence may have been cause for voting to close this as off topic. I think this question (minus the request for links to other resources), is spot on for this community, however as the question stands it is too broad to answer. Can you provide a specific use case that might be giving you problems? Commented Jul 30, 2018 at 0:00
  • @GregBurghardt unfortunately I have no concrete case I'm analyzing the daily work. I have noticed that few are not clear when to use one or the other method. And I wanted a comparison with more experienced people. I have an example now I write it!! Commented Jul 30, 2018 at 6:28

1 Answer 1

5

The simplest way to decide if the dependency (something you need) belongs in the constructor or method parameter list is when you know it.

If you know it before you need it consider making an object to hold it and use a constructor to pass it in.

If you know it when you need to use it consider passing it directly to the method that uses it.

If you only know it after the object has been constructed but before you use it or need to remember it after you use it, first consider creating a new object to hold it until you need it. If not that, then setters may be what you need.

This approach lets you be as immutable as you can which makes understanding the code easier.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.