Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Guice's @ImplementedBy evil? Is it appropriate in some cases?

Tags:

java

guice

I've heard claims that "@ImplementedBy is evil", on grounds that it breaks DI concepts and makes the interface aware of its implementors.

This might be true in some cases, but often I found that it just leads to cleaner code (no long Modules to maintain), while not really hurting anything in the process.

As pragmatics, not purists, when do you think it's worthwhile to use @ImplementedBy?

like image 774
ripper234 Avatar asked Jun 01 '11 06:06

ripper234


1 Answers

I had the same ugh, ick, yuck feeling of @ImplementedBy BUT at the same time, it's very useful. Spring has to scan all classes in the package list you give it. In Guice you don't have to configure that package list to scan and @ImplementedBy is key for that(if not using the Binder to bind that is). AS it goes down your object heirarchy on the first Injector.getInstance, and hits an interface, it then uses the @ImplementedBy to find the default implementation(as long as there is nothing in the Binder overriding that default).

We use @ImplementedBy as well. We find it extremely nice to use, it is a bit ugh, but it just works and works nicely and since it's DI, it is not really depending on the implementation since you can override bindings with new ones anyways.

At the same time interfaces are generally used less and less with DI frameworks. All the DAO interfaces went away on our project AND we can still swap in mock objects for the DAO. The java classes are implicit interfaces to begin with that can be mocked without needing the interface. We now reserve interface use for main apis to be very clear and not clutter it with implementation code. For DAO's we have not needed this anymore.

like image 147
Dean Hiller Avatar answered Sep 23 '22 20:09

Dean Hiller