Answer the question
In order to leave comments, you need to log in
Dependency Injection (Which way is better to use)?
For some reason, I didn’t really think about it before, but now I started to notice this and it puzzled me, what is better to use and what could be the consequences? Logic leans more towards the second option, however, tests and all that ...
Handler(Main main) {
this.main = main;
this.service = main.getService()
}
//или
Handler(Main main, Service service) {
this.main = main;
this.service = service;
}
Answer the question
In order to leave comments, you need to log in
The 1st option is valid if it were like this:
Handler(ServiceFactory factory) {
this.factory = factory;
this.service = factory.createService()
}
the second option, since in the first case the service depends on Main, in the second case you can substitute any desired service
The second one is better of course, but in both cases it is a "manual" DI. Like it or not, somewhere there is a dependency on the Main and Service constructors. Ideally, DI should not be handled by you, but by some framework and / or utilities that generate code, and then it will be something like this:
@Inject Main main;
@Inject Service service;
Handler(){
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question