I (think I) understand the purpose of dependency injection, but I'm just not getting why I need something like Guice to do it (well, obviously I don't need Guice, but I mean why it would be beneficial to use it). Let's say I have existing (non-Guice) code that's something like this:
public SomeBarFooerImplementation(Foo foo, Bar bar) {
this.foo = foo;
this.bar = bar;
}
public void fooThatBar() {
foo.fooify(bar);
}
And somewhere higher level, maybe in my main(), I have:
public static void main(String[] args) {
Foo foo = new SomeFooImplementation();
Bar bar = new SomeBarImplementation();
BarFooer barFooer = new SomeBarFooerImplementation(foo, bar);
barFooer.fooThatBar();
}
Now I've basically got the benefits of dependency injection, right? Easier testability and so forth? Of course if you want you could easily change the main() to get implementation classnames from configuration instead of hardcoding, too.
As I understand it, to do the same in Guice, I'd do something like:
public SomeModule extends AbstractModule {
@Override
protected void configure() {
bind(Foo.class).to(SomeFooImplementation.class);
bind(Bar.class).to(SomeBarImplementation.class);
bind(BarFooer.class).to(SomeBarFooerImplementation.class);
}
}
@Inject
public SomeBarFooerImplementation(Foo foo, Bar, bar) {
this.foo = foo;
this.bar = bar;
}
public static void main(String[] args) {
Injector injector = Guice.createInjector(new SomeModule());
Foo foo = injector.getInstance(Foo.class);
barFooer.fooThatBar();
}
Is that it? It seems to me like just syntactic sugar, and not particularly helpful syntactic sugar. And if there's some advantage to breaking the "new XxxImplementation()" stuff out into a separate module rather than doing it directly in main(), that's easily done without Guice anyway.
So I get the feeling that I'm missing something very basic. Could you please explain to me how the Guice way is advantageous?
Thanks in advance.