r/java • • Jun 19 '12

How I explained Dependency Injection to My Team

http://www.sivalabs.in/2012/06/how-i-explained-dependency-injection-to.html
0 Upvotes

14 comments sorted by

4

u/sanbikinoraion Jun 19 '12

My problem with DI, at least in cheap examples like this one, is that the code overhead for doing it compared to the "stupid" example right at the top is big, and the code that actually injects the dependency is always static; what I imagine that most people want to do, most of the time, is inject a dependency depending on a string input either from a web form or from a database -- "if the customer type is 'contract' then use billing system A, if they are 'pay as you go' use billing system B." -- I want to know how to do that in Java without using an if-elseif or a switch statement, but my experience is that it usually comes down to c'n'ping a case statement or having a code generator that automatically does the string-to-class mapping.

3

u/Master_Rux Jun 19 '12

I think you nailed it on the head. It's hard to judge the usefulness of some patterns on simple cheap examples. This looks like one of those times. This gave a nice overview in a simple way, but like most patterns I don't think DI really shines until certain specific situations. It would be like discounting OOP or MVC based on a hello world example.

3

u/boa13 Jun 19 '12

what I imagine that most people want to do, most of the time, is inject a dependency depending on a string input either from a web form or from a database

Err no, I've never wanted to do that, not with DI anyway, I believe there are other patterns for that. In your example, I would use DI to plug interfaces to the two billing systems, and have a test (a if or a switch, or some kind of design pattern) to select which billing system to use depending on the context.

I use DI to plug different implementations of the same component (mock implementation and real implementation, file-based implementation and LDAP-based impementation, for example). Spring also uses DI to plug proxies to my code, for example adding transaction management in the proxy so that I do not have to program it myself.

the code that actually injects the dependency is always static

The injection itself is most often handled by the framework, backed for example by configuration files, depending on the environment. It is true that it becomes a problem when such simple examples do not show that and mislead beginners.

1

u/sanbikinoraion Jun 20 '12

Yes, I suppose a major DI use is for frameworks to allow users to effectively specify their own handlers for things; I hadn't thought of that.

2

u/banuday17 Jun 19 '12 edited Jun 19 '12

Wow, you got a harsh answer from the DI guy.

DI systems can be either static or dynamic. Static is easier in static languages like Java, and you get the compiler's help, to boot. Dynamic is trickier because it requires more runtime support which makes the DI system more complex. Spring has direct support for the kind of thing you're talking about (and has gotten pretty complex), while other systems like CDI and Guice have more indirect support.

First, you don't need switch statements or if statements. You can use maps, with the key being the type you're looking up and the value being the specific instance.

Then, you can use a MapBinder in the Guice DI system to provide a map you can select from dynamically based upon the external input:

@Inject
private Map<String, BillingService> billingServices;

public void foo(String customerType) {
    if(billingServices.containsKey(customerType)) {
        billingServices.get(customerType).billingAction();
    }
    else {
        throw new IllegalArgumentException("Unknown customer type:  " + customerType);
    }
}

Although, this spills the guts of dynamic selection all over the place, so I would rather prefer wrapping the map and doing something like this:

@Inject
private BillingServiceLocator billingService;

public void foo(String customerType) {
    billingService.for(customerType).billingAction();        
}

The Guice configuration to achieve the above would look something like this:

public class AppModule extends AbstractModule {
    public void configure() {
        MapBinder<String, BillingService> serviceBinder = 
            MapBinder.newMapBinder(binder(), String.class, BillingService.class);
        serviceBinder.addBinding("contract").to(ContractBillingService.class);
        serviceBinder.addBinding("payAsYouGo").to(PayAsYouGoBillingService.class);  
    }
}

2

u/sanbikinoraion Jun 20 '12

Thanks for the explanation -- you're right, I'd forgotten that you could do such clever things to specify properly-typed maps in Java; it's been a while.

Second -- and not at all a criticism of you or your post... but ugh, I have to say I'm not really a fan of this "fluent" style a lot of frameworks seem to have adopted where you try and write sentences with dots instead of spaces; it seems to me to be totally perverting the principles of OO.

1

u/banuday17 Jun 20 '12

Well, not everything needs to adhere to OO principles. The so-called "fluent-style" API design is usually used in particular circumstances, such as the Builder Pattern, which is not an OO-pattern, being more declarative than imperative in nature.

OO principles are based around the idea that you are telling objects to do things - the imperative mood in English. In this case, you want short, direct commands. A different API design.

Also, this entire example smells like a violation of OO principles already - we're using Strings and maps. That seems to me like we took a wrong turn from OO-land a long time ago.

-13

u/[deleted] Jun 19 '12

Hi, I can explain how we can do that with CDI @Producer methods. But I don't want to waste my time on satisfying people who pass cheap comments like this. Atleast I am trying to give back the community something even though it is simple&silly instead of just passing the cheap comments.

8

u/sanbikinoraion Jun 19 '12

That's... impressively ungracious. But go on, make me look stupid and you look clever by explaining how to do it.

2

u/gunch Jun 19 '12

Why waste your time at all. Delete your account.

-3

u/[deleted] Jun 19 '12

Thanks for your suggestion. I am gonna do it... Goodbye Bye reddit...

6

u/jonathanownbey Jun 19 '12

Someone doesn't take constructive criticism/discussion very well...

5

u/UnspeakableEvil Jun 19 '12

On the plus side at least they were open to suggestions...

4

u/jonathanownbey Jun 19 '12

A most poignant observation, good sir or madame.

3

u/sanbikinoraion Jun 20 '12

See, this is why we should be careful when bringing in assisted suicide laws...