B
B
BRONNER2014-09-20 22:22:20
Programming
BRONNER, 2014-09-20 22:22:20

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

3 answer(s)
S
Sergey, 2014-09-21
@BRONNER

The 1st option is valid if it were like this:

Handler(ServiceFactory factory) {
        this.factory = factory;
        this.service = factory.createService()
    }

if both services exist in a single copy - then the second option. If you need to make templates like Registry and store a pool of services there, then again, as in the case of factories, the first option.

P
Pavel Solovyov, 2014-09-20
@pavel_salauyou

the second option, since in the first case the service depends on Main, in the second case you can substitute any desired service

F
FoxInSox, 2014-09-21
@FoxInSox

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 question

Ask a Question

731 491 924 answers to any question