A beginners guide to Dependency Injection

Discussions

News: A beginners guide to Dependency Injection

  1. Dependency Injection continues to grow in popularity due to it's code simplification effects. If you've haven't had a chance to learn and apply DI yet, this new article on TSS by Dhananjay Nene will bring you up to speed on the concepts as well as illustrate how DI is done in Spring, PicoContainer, Hivemind, and XWork.

    Read: A beginners guide to Dependency Injection

    Threaded Messages (55)

  2. one thing,[ Go to top ]

    Seems like a nice article. one comment, if i am not mistaken you can actually make the Spring configuration much simpler by not writing the "singleton=true" and eliminating (some) bean property definitions with an "autowire" attribute.
  3. one thing,[ Go to top ]

    Not only that, but there is a terser syntax for expressing properties these days without using nested tags, eg:

    <beans>
    <bean id="AirlineAgency" class="com.dnene.ditutorial.common.impl.SimpleAirlineAgency"/>
    <bean id="CabAgency" class="com.dnene.ditutorial.common.impl.SetterBasedCabAgency">
    <property name="airlineAgency" ref="AirlineAgency"/>
    </bean>
    <bean id="TripPlanner" class="com.dnene.ditutorial.common.impl.SetterBasedTripPlanner">
    <property name="airlineAgency" ref="AirlineAgency"/>
    <property name="cabAgency" ref="CabAgency"/>
    </bean>
    </beans>
  4. Gothically[ Go to top ]

    ...
  5. Re: Gothically[ Go to top ]

    Cammenti rulyat!!!
  6. Printer friendly[ Go to top ]

    The "Printer Friendly" URL is not working.

    Thanks.
  7. Printer friendly[ Go to top ]

    Forwared To: webmaster@theserverside.com
  8. Which to use[ Go to top ]

    Personally after looking at the examples, I am still convinced that PicoContainer is probably the way to go when doing DI at least if you have control over the source (or not, there are adapters to Pico to allow XML data loading).

    The main advantage for me is compile time checks. If PicoContainer releases a Generics version it would also have type safety as well.

    Other advantage of being in code is it makes things easier to the "rename" or "move to package" refactoring since its just code that Eclipse or other refactoring capable IDEs can handle.

    I'm kind of biased though, I've been using PicoContainer in my current project http://twiff.sf.net/modules/picoservlet which extends the Servlet API to support dependency injection.
  9. Which to use[ Go to top ]

    Personally after looking at the examples, I am still convinced that PicoContainer is probably the way to go when doing DI at least if you have control over the source (or not, there are adapters to Pico to allow XML data loading).

    I would, without reservation, recommend Spring. One of the reasons is the integration of Spring with other systems that use DI. I find the combination of Spring with JSF to be extremely powerful, especially when enhanced with jsf-spring (jsf-spring.sourceforge.net).
    Other advantage of being in code is it makes things easier to the "rename" or "move to package" refactoring since its just code that Eclipse or other refactoring capable IDEs can handle.

    Eclipse refactoring can deal with references to class and package names in XML (and other) file, as well as in Java source.
  10. Can anyone name a real-world scenario where I would be justified in adding this extra level of complexity?

    Under what circumstances should I be willing to suffer such a huge performance hit?

    Jonathan Allen
  11. Can anyone name a real-world scenario where I would be justified in adding this extra level of complexity?Under what circumstances should I be willing to suffer such a huge performance hit?

    Jonathan, is your question regarding performance, or complexity? For the latter, DI simplifies your code, not makes it more complicated. All this stuff is logic you would have had to have written anyway, but now you can take it out of the code and let a standard framework handle it. also see Rod Johnson's Spring article for more examples of how DI can impact your code.

    For performance - I'm not sure that there is a hit. The perf impact of getting a bean from a factory rather than new() is negligible.
  12. I find that DI provides a lot of benefit when unit testing your code. Specifically:

    -- It is much easier to isolate the code under test if you don't need to worry about the code going out and instantiating and initializing a lot of collaborators, or, worse, trying to locate collaborators in a JNDI context.

    -- If you want to use mock objects to validate that your class is interacting correctly with its collaborators, you have a nice straight forward way to inject the mock into the class under test. If the class under test is creating or locating its own collaborators, it is harder to convince it to use a mock.

    Also, while not related to unit testing:

    -- If you are using multiple source code trees to guarantee at compile time that various modules are isolated from each other, you can use DI at run time to wire together objects that shouldn't know any more about each other than the interfaces they implement.

    -- You get a straight forward way to do runtime AOP and decoration, as distinct from compile time approaches like AspectJ. Spring uses this nicely with declarative trasaction semantics.

    Lastly, I'll add that most of what I've seen containers manage are singletons, and there has been no performance impact from using the DI approach.
  13. Jonathan, is your question regarding performance, or complexity? For the latter, DI simplifies your code, not makes it more complicated. All this stuff is logic you would have had to have written anyway, but now you can take it out of the code and let a standard framework handle it.

    I still can't keep myself smiling about statements like this. Still IoC is nothing but "push configuration for interfaces" so what you actually save is the call to "factory.getInstance(...)" in your code.

    On top of that you would of course save coding the factories themselves, but I doubt that it is not possible to come up with a nice design pattern for factories using interesting concepts like inheritance.

    BTW: As soon as you build everything using factories, unit testing becomes about as easy as with any IoC framework. The beauty is in the POJO interface driven approach, not in the mechanism of configuration here.

    Of course, there are downsides as well. For example it is less clear from the code, where is a singleton and where is a standalone instance. You need the configuration for that.
    You also need to write the configuration which introduces effectively another language (albeit a simple one). Of course that realized, frameworks provide you with sick things like "autowiring" (don't get me started...).
     
    Spring as such is not so much about IoC but about being an application framework (featuring some basic AoP and several components for accessing data bases, other frameworks etc.).
  14. BTW: As soon as you build everything using factories, unit testing becomes about as easy as with any IoC framework. The beauty is in the POJO interface driven approach, not in the mechanism of configuration here.
    POJO interfaces making unit testing is undeniable. However, using a DI framework to wire up the framework differently (e.g. to test scenarios with alternative services or "nulled out" services) can indeed make testing easier.
    For example it is less clear from the code, where is a singleton and where is a standalone instance.

    You can find the complete source at http://dnene.com/files/DependencyInjection.zip. I have requested TSS to add a reference to the source.
    Spring as such is not so much about IoC but about being an application framework (featuring some basic AoP and several components for accessing data bases, other frameworks etc.).

    Actually spring is indeed a lot about DI/IOC. The study of spring is interesting in terms of it being both a DI framework, and also simultaneously being a very significant DI consumer/user (e.g. the various other components you have described above). Spring has a very extensible capability in being able to allow users to add their own components into the framework. The ease with which such extensibility is offered, is partially / substantially (depending on one's point of view) due to the way it leverages its own DI framework capabilities.
  15. But why would I want to use this?[ Go to top ]

    You can indeed use a nice inheritence pattern for IoC. IoC containers are a preference rather than a neccessity.

    Instead of defining your dependency as such:

    public class MyShop {

      private ShoeStore shoeStore = null;
      private ShirtStore shirtStore = null;
      private PantStore pantStore = null;

      public void setShoeStore(ShoeStore shoeStore) {
        this.shoeStore = shoeStore
      }

      public void setShirtStore(ShirtStore shirtStore){
        this.shirtStore = shirtStore
      }

      public void setPantStore(ShirtStore shirtStore){
        this.pantStore = pantStore
      }

    }

    You can instead define your dependencies as such:

    public class MyShop {

     public interface Context {
       public ShoeStore getShoeStore();
       public ShirtStore getShirtStore();
       public PantStore getPantStore();
     }

     private final Context context;

     public MyShop(Context cxt) {
       this.context = cxt;
     }
    }

    You can then implement MyShop.Context anywhere you want - Implement it in a different package and jar if you want - drop in a different jar and your application is wired up differently. Have a separate package for your all your JUnit Mock Context implementations etc. Clarity and separation of your wiring up code is easy.

    You have the full power of OO and Java at your disposal for wiring up your application. You can extend other Contexts, abstract out common Contexts etc. You can combine the implementation of all your Contexts into one object, into a few objects or implement each Context separately. Reuse Context implementations with generalization, composition etc. The code inside the implementation of a Context is generally minimal - amounts to declaring a member variable and returning it in a getter.

    Finally, your wiring-up code is compile time verified (a preference of mine personally). If you are dropping in a new jar of your wire-up - compile it and verify first.

    See article: http://www.theserverside.com/articles/content/IOCandEJB/article.html
  16. [...] let a standard framework handle it

    Could please explain what you exactly mean with "standard framework"?
    [...] DI simplifies your code, not makes it more complicated

    I guess it depends on what you actually consider being "code". As far as I have seen, most of the IoC Frameworks require some kind of configuration (usually in form of XML files). I would consider those artifacts also as some kind of "code", which IMHO is not neccessarily less complex than the code you would have originally written.

    Regards,
        Dirk
  17. But why would I want to use this?[ Go to top ]

    As far as I have seen, most of the IoC Frameworks require some kind of configuration (usually in form of XML files). I would consider those artifacts also as some kind of "code", which IMHO is not neccessarily less complex than the code you would have originally written.
    It's about striking a balance between what's in Java code and what isn't. Sure, it's impossible to magically remove all configuration information, unless you want to end up with a lot less power than you had in Java code in the first place. But if you strike a good balance between Java code and external configuration (which we believe Spring does), you gain a lot of power to vary application wiring for different scenarios and you can tap into many container value adds which mean that a lot of Java code does simply go away without needing replacement in XML or other metadata. E.g. JNDI lookups or business delegates (if accessing EJBs) never need to be written in Java code, as they can be replaced by a trivial XML alternative using a Spring FactoryBean.

    Rgds
    Rod
  18. As far as I have seen, most of the IoC Frameworks require some kind of configuration (usually in form of XML files). I would consider those artifacts also as some kind of "code", which IMHO is not neccessarily less complex than the code you would have originally written.
    It's about striking a balance between what's in Java code and what isn't. Sure, it's impossible to magically remove all configuration information, unless you want to end up with a lot less power than you had in Java code in the first place. But if you strike a good balance between Java code and external configuration (which we believe Spring does), you gain a lot of power to vary application wiring for different scenarios

    Sure IOC and having the wiringup separated out is good. I know that and understood it to a great deal thanks to Spring. But what is the advantage of doing this in a generic xml language? Why not use a Java class ie JavaDefaultContext with a lot of getters which do exactly the same thing as the <bean> tags do in a applicationContext.xml - instantiating and wiring.

     
    ... and you can tap into many container value adds which mean that a lot of Java code does simply go away without needing replacement in XML or other metadata. E.g. JNDI lookups or business delegates (if accessing EJBs) never need to be written in Java code, as they can be replaced by a trivial XML alternative using a Spring FactoryBean.RgdsRod

    With a bit of effort I think you could even build a small container api, which together with anotations can instrument such an 'ApplicationContext.class' to provide all the things a IOC Framework provides ie postprocessing, init/destroy, interceptor adding, string based lookup etc.

    In Java I even doupt that you would need a lot of FactoryBeans. Most of the time straight simple static helpers would be sufficient.

    I only see one advantage of xml and this is no recompile (like with any other scripting language).

    Christian
  19. http://www.theserverside.com/news/thread.tss?thread_id=34167#176945
  20. http://www.theserverside.com/news/thread.tss?thread_id=34167#176945

    Thanks for the link. This context-constructor-ioc pattern is certainly a way you could go. But it has real defficencies over containers:
    - It does not provide the main reason I use a Containers that is transaction interception.
    - other container-services like (restricted) livecycle etc are not supported as well.
    - While I consider it is a bad practice, others think recursive dependencies are needed.
    - If you get a lot of different beans(components) than you could get method-naming conflicts in the interfaces (There is no form of namespaces or a single place to keep all these names separate)

    I like containers. I prefer Hivemind but more often use Spring because of the as everyone knows excellent library. I just wonder why as stated above I can not write the 'container-definition' in later instrumented java.

    Christian
  21. People have a tendency of mixing AOP with IoC. Externally managed transactions are achieved with AOP or an EJB container (which is not an IoC container).
  22. But why would I want to use this?[ Go to top ]

    People have a tendency of mixing AOP with IoC. Externally managed transactions are achieved with AOP or an EJB container (which is not an IoC container).

    I think his point is that Spring integrates off of the above and your solution does not. Your solution, from what I read, doesn't handled declarative access to neither the Spring integrated features, nor DI features.

    Personally, I prefer the declarative approach Spring advocates.
  23. IoC and AOP[ Go to top ]

    IoC and AOP are enabling techniques that compliment each other. IoC gives you centralized, declarative "push"-style object configuration. AOP gives you dynamic, targeted object decoration (aspects). You leverage IoC to centralize the configuration of these aspects and the situations in which they apply.

    IoC+AOP+DeclarativeServices = Power Pojos

    Keith
  24. But why would I want to use this?[ Go to top ]

    People have a tendency of mixing AOP with IoC
    You sound as if you think this is a bad thing. As Keith puts out, it's really necessary to combine the two to achieve a POJO programming model in real-world applications. Sure, they're separate concepts, but in the end results are more important than concepts and the two work beautifully together in practice.

    In the case of Spring, IoC and AOP are designed to work together, although the IoC container doesn't need to know anything in its implementation about the AOP mechanism.

    Rgds
    Rod
  25. Why not use a Java class ie JavaDefaultContext with a lot of getters which do exactly the same thing as the <bean> tags do in a applicationContext.xml - instantiating and wiring.&nbsp;

    Does this do anything for you?

    StaticApplicationContext
  26. If you think about IoC containers as just a way to instantiate objects and connect them together, you are missing the forrest for the trees.

    The value of Spring and HiveMind is the almost invisible value-adds:

    Thread safety is pervasive, inherent, and automatic. You have no concern for which services are instantiated first, it all just works.

    Dynamic Binding is well integrated, meaning you don't always know at build time which collaborater will be plugged in. This is at the core of implementing GoF Strategy pattern, for example.

    Documentation both HiveMind a Spring can produce concise, off-line documentation of a system.

    AOP: HiveMind and Spring both support AOP features, meaning that you can build a service which is more than the sum of its parts (that is, more than just an interface and an implementation).

    Less code: Via AOP features, injection, and alternate factories you write less code, leading to a more robust system. Alternate factories: In many cases, HiveMind can create the implementations of your services from the service interface directly, in combintation with some configuration information. This is how HiveMind facilitates GoF Chain-Of-Command and Strategy, as well as the Pipline pattern (think Servlet + ServletFilter).


    People who don't build real systems often think that a little bit of Java code can do what an IoC container can. Ten years ago, people thought that a little bit of C++ code could do what the Java GC can do. Both are wrong; when you program in a scalable, testable way you use lots of objects with intricate connections between them, and you need an IoC container to do that connecting.

    IoC containers defuse (cyclic) dependencies, simplify interfaces, and run more efficiently. Yes, more. Brute-force approaches are either non-thread safe, or use excessive amounts of synchronization. HiveMind (for example) builds a proper two-level proxy that provides just-in-time instantiation with thread-safety (without requiring synchronization on every method invocation, after the service is created). You aren't going to do that when writing you own code if you even write just-in-time creation proxies in the first place.

    When I see people say "just use statics" I cringe; statics are dangerous in a threaded environement, especially inside an application server. They get in the way of redeployment, undeployment, and GC.
  27. isn't the world static :)[ Go to top ]

    When I see people say "just use statics" I cringe; statics are dangerous in a threaded environement, especially inside an application server. They get in the way of redeployment, undeployment, and GC.

    sorry, I couldn't resist making a joke. why should anyone care about static stuff, it's not like things change :)

    peter
  28. Dependency Injection in J2EE 5.0[ Go to top ]

    Read my blog entry Dependency Injection and J2EE 5.0 to know how dependency injection will be supported in J2EE 5.0.

    Also you can try out the dependency injection sample in the EJB 3.0 preview page

    -Debu
  29. Dependency Injection in J2EE 5.0[ Go to top ]

    Which kind of emphasises the point that discussing DI as something "different" is moot. It's now a commodity as we see from both EJB 3.0 and JSF. The best of breed IoC containers are adding functionality over and above the dependency injection being discussed here.
  30. But why would I want to use this?[ Go to top ]

    [...] let a standard framework handle it
    Could please explain what you exactly mean with "standard framework"?
    [...] DI simplifies your code, not makes it more complicated
    I guess it depends on what you actually consider being "code". As far as I have seen, most of the IoC Frameworks require some kind of configuration (usually in form of XML files). I would consider those artifacts also as some kind of "code", which IMHO is not neccessarily less complex than the code you would have originally written.Regards,&nbsp;&nbsp;&nbsp;&nbsp;Dirk

    It is true that there is still this code. The point for me is that it is separated out. It has taken me quite a while to get to see the point of IoC, but now I do I can really see what it is for. It is the next step in making code simpler and more maintainable. Without IoC your classes have to contain both whatever is their main functionality (perhaps business logic) and also code to create and maintain links to other classes that they use. IoC means that the only code needed in classes intended for business logic is business logic. Sure, you can write additional Factory classes to bind all the classes together, but there is little point when existing IoC frameworks do all this for you.

    IoC can certainly be justified in terms of being able to do testing, or to assist with AOP etc., but for me it is a good thing even by itself, as the more that different aspects of an application are cleanly separated, the easier code is to understand and maintain.

    Regarding the different frameworks, I am personally not in favour of those that require interfaces. For me, interfaces are there to allow alternative implementations of an API. I may have a simple class that provides only a few methods. To have to provide an interface for this class to implement seems pointless if the class is small and it is the only class that conforms to that interface. This is why I prefer, for example, Spring.
  31. But why would I want to use this?[ Go to top ]

    Regarding the different frameworks, I am personally not in favour of those that require interfaces.
    I think it comes down to enabling the use of legacy code above all. A new framework is less useful the more it requires rework of existing assets. So while programming to interfaces rather than classes is a well-known best practice dating back years (advanced in the GoF book and elsewhere), sometimes it's just not possible without too much rework. Spring recognizes that, which is also why it supports both Setter and Constructor injection, instantiation of objects from factory methods and many other non-obvious scenarios. And of course sometimes it's overkill. Although I have to say that I often end up refactoring to introduce interfaces anyway, if I'm writing new code...
  32. But why would I want to use this?[ Go to top ]

    And of course sometimes it's overkill
    To make myself clear (I edited in another sentence without rereading the whole post)...

    "And of course sometimes the use of interfaces rather than classes is overkill."
  33. But why would I want to use this?[ Go to top ]

    So while programming to interfaces rather than classes is a well-known best practice dating back years (advanced in the GoF book and elsewhere), sometimes it's just not possible without too much rework.

    I have to admit that I am more resistant to some of these best practices that I should be. I used to be a Smalltalk developer; an environment where classes are very dynamic and lightweight. The idea of writing to an interface for a very small class that might have only a few methods (and is only there to clarify things and not to provide anything I would personally term a 'service'), seems clunky and unnecessary. I guess I shall get over these bad habits with time!
    Spring recognizes that, which is also why it supports both Setter and Constructor injection, instantiation of objects from factory methods and many other non-obvious scenarios.

    And I have to say that Spring's 'we'll support any way you want to do it' attitude is one of the reasons I find it so appealing.
  34. Programming to Interfaces[ Go to top ]

    So while programming to interfaces rather than classes is a well-known best practice dating back years (advanced in the GoF book and elsewhere)....

    This is nitpicking (and getting off topic), but the GoF were not advocating literally programming everything to a Java interface (i.e. a construct created with the Java 'interface' keyword). They were using C++ and Smalltalk after all. They were using the word 'interface' in the sense of programming to an abstraction. An 'interface' in that sense can be created using an abstract class, or even be implicit, a la Ruby duck typing. The point is, if you have a choice between coding to ArrayList or List, use List. And if you can use Collection instead, even better. It's better because programming to the higher level abstraction, which shields you from changings to the lower level concept. It doesn't really matter if Collection and List are literally Java interfaces, abstract classes, concrete classes, C++ template traits, or whatever. Some folks, like Martin Fowler, point out that abstract classes can be handy because you can add a bit of implementation. Certainly when there is exactly one implementation for every interface, then things have gone haywire. That makese the system harder to maintain, as the same signature change as to be made to two places (to the interface and the implementation), and the interface provides no abstraction as it's identical to the public methods of the class. Too many interfaces just clutter things up.

    We can go round and round about when to use interfaces vs. abstract classes (or both), whether Java's solution to the multiple inheritance problem (interfaces) is better that Ruby's modules, or whether Python got it right by just allowing multiple inheritance. But the point is the GoF never meant the phrase 'programming to an interface' to be interpreted literally as 'use Java interfaces everywhere'.

    I think the real reason frameworks like Spring, JMock, EasyMock, etc encourage you to use interfaces is that at least in their early versions they were using the JDK proxy API, which only works with interfaces. Now with CGLib we have more choices, which is good, although at least with EasyMock mocking interfaces still seems to work better. But the reasons are technical and could change with time.
  35. Programming to Interfaces[ Go to top ]

    So while programming to interfaces rather than classes is a well-known best practice dating back years (advanced in the GoF book and elsewhere)....
    This is nitpicking (and getting off topic), but the GoF were not advocating literally programming everything to a Java interface (i.e. a construct created with the Java 'interface' keyword). They were using C++ and Smalltalk after all. They were using the word 'interface' in the sense of programming to an abstraction. An 'interface' in that sense can be created using an abstract class, or even be implicit, a la Ruby duck typing. The point is, if you have a choice between coding to ArrayList or List, use List. And if you can use Collection instead, even better. It's better because programming to the higher level abstraction, which shields you from changings to the lower level concept. It doesn't really matter if Collection and List are literally Java interfaces, abstract classes, concrete classes, C++ template traits, or whatever. Some folks, like Martin Fowler, point out that abstract classes can be handy because you can add a bit of implementation. Certainly when there is exactly one implementation for every interface, then things have gone haywire. That makese the system harder to maintain, as the same signature change as to be made to two places (to the interface and the implementation), and the interface provides no abstraction as it's identical to the public methods of the class. Too many interfaces just clutter things up. We can go round and round about when to use interfaces vs. abstract classes (or both), whether Java's solution to the multiple inheritance problem (interfaces) is better that Ruby's modules, or whether Python got it right by just allowing multiple inheritance. But the point is the GoF never meant the phrase 'programming to an interface' to be interpreted literally as 'use Java interfaces everywhere'.I think the real reason frameworks like Spring, JMock, EasyMock, etc encourage you to use interfaces is that at least in their early versions they were using the JDK proxy API, which only works with interfaces. Now with CGLib we have more choices, which is good, although at least with EasyMock mocking interfaces still seems to work better. But the reasons are technical and could change with time.

    Well, the point about GOF, I think, is a given considering how that book preceded Java. I think everyone's point we all think you can have to much of a good think. Some classes simply don't need interfaces.

    However, I think Spring always allowed for proxying by class and by interface, so I don't believe that they made any decisions because of the Proxy. I think that they encourage interfaces because using them is probably the right thing to do. Worst case, a tool like IDEA will allow you to extract the interface later.

    I personally take a page from Joshua Bloch's Effective Java and use an interface with an abstract implementation.
  36. Programming to Interfaces[ Go to top ]

    However, I think Spring always allowed for proxying by class and by interface, so I don't believe that they made any decisions because of the Proxy.

    That's good to know. I retract my earlier statement!
    Worst case, a tool like IDEA will allow you to extract the interface later.

    Which is why you don't always need to create it up front. YAGNI.
    I think that they encourage interfaces because using them is probably the right thing to do.

    Well, *probably*, more often than not, I guess. But I don't like equating interfaces with goodness. Sometimes they're not the best choice. More to my point, to represent an abstraction as an interface or not is a much narrower issue than what the GoF were getting at with the phrase 'program to an interface'. You can use the Java interface keyword and still miss their point. Their point was deeper. If we use the GoF in support of interfaces vs. abstract classes (or both), we risk missing their larger point about programming to abstractions not implementations.

    If there's a one to one correspondence between interface method and public implementation method, and only one class implements the interface, and every time you change the interface you change the class, and the interface is fatter than it needs to be (i.e. some clients only need a few methods of the interface, and thus you really want several narrower interfaces), then you're not really programming to an abstraction, even though you are literally 'programming to a [Java] interface'.
    I personally take a page from Joshua Bloch's Effective Java and use an interface with an abstract implementation.

    I use this technique too. Don't get me wrong, I use interfaces a lot. It's especially usefull with TDD and testing with mock objects. You create an interface that your class under test needs, even before creating the concrete class. Thus the interface specifies exactly, and only, what your client needs.

    The most compelling argument for using an interface in Java is that a class can only extend one super class, but can implement many interfaces. So if your concept is something that might be usefully 'mixed in' to another class, like 'Serializable', then an interface is almost required.

    My only (minor) semantic point is that when the GoF said 'program to an interface', they meant 'interface' in the sense of the set of public messages that the object will respond to. Program to an abstraction, not an implementation. Using a Java abstract class could, in a given situation, satisfy the GoF's recommendation re programming to an interface. The much narrower question of whether to *literally* use a Java interface or not is not answered by quoting the GoF. That's not what they meant by 'progamming to an interface'.
  37. What more can I say, thanks Stephen for pointing out the facts!

    Indeed, the GoF were talking about situations with multiple implementations for the same abstraction, in which case it's obvious that one should "program to the interface, not the implementation".

    More than that, the whole context of GoF is "reusable object-oriented software". It does not make any sense to create a separate interface (abstraction) for a specific service class, if you know that there will always be exactly one implementation (except for unit testing with EasyMock or jMock, but this is only so because of these tools' limitations).

    Isn't it strange that other great principles, such as "favor composition over inheritance" and "encapsulate the concept that varies", are rarely, if ever mentioned at TSS?

    And finally, concerning "do the simplest thing that can possibly work": isn't using the "new" operator the simplest way to obtain a dependency? ;)

    Rogerio
  38. Programming to Interfaces[ Go to top ]

    I think the real reason frameworks like Spring, JMock, EasyMock, etc encourage you to use interfaces is that at least in their early versions they were using the JDK proxy API, which only works with interfaces.
    This is not the case with Spring. I advocated the use of interfaces before founding Spring.

    Anyway, Spring IoC doesn't create proxies by default; only if they're needed to apply declarative services.

    Rgds
    Rod
  39. Programming to Interfaces[ Go to top ]

    I think the real reason frameworks like Spring, JMock, EasyMock, etc encourage you to use interfaces is that at least in their early versions they were using the JDK proxy API, which only works with interfaces.
    This is not the case with Spring. I advocated the use of interfaces before founding Spring. Anyway, Spring IoC doesn't create proxies by default; only if they're needed to apply declarative services.RgdsRod

    Sorry, I officially retract my statement and eat my words!
  40. Under what circumstances should I be willing to suffer such a huge performance hit?Jonathan Allen

    Can you please elaborate on the huge performance hits you have encountered.
  41. Performance[ Go to top ]

    Jonathan
    Under what circumstances should I be willing to suffer such a huge performance hit?
    Presumably you are referring to the use of reflection to configure objects? That typically happens only when the container starts up: i.e., once only with zero impact on performance once the app is running.

    For "prototype" or non-singleton objects, supported by Spring and other popular IoC containers, wiring can occur at runtime, but this typically accounts for a minority of objects (2-5%). In any case, initializing resources that objects use costs way more time than the use of reflection, which is extremely fast in modern JVMs.

    If you have a real-world story of negative performance impact of Dependency Injection, rather than speculation, I'd love to hear it. (I suspect it would result from misuse of the technology.) I've never seen or heard of any negative performance impact in many projects I've been involved in, from simple web applications up to extreme enterprise middleware.

    Rgds
    Rod
    Interface21 - Spring from the Source
  42. Same old story...[ Go to top ]

    ...though differently told. A neat and lightweight way of configuring interface factories. I have one question though : since we're (rightfully) using defined interfaces for communication between the service and the client, why would you use constructor based dependencies ? Constructor signature can't be part of an interface definition last time I checked... But maybe I'm missing something.

    Regards

    François
  43. Same old story...[ Go to top ]

    ...though differently told. A neat and lightweight way of configuring interface factories. I have one question though : since we're (rightfully) using defined interfaces for communication between the service and the client, why would you use constructor based dependencies ? Constructor signature can't be part of an interface definition last time I checked... But maybe I'm missing something.RegardsFrançois

    Dependency Injection does not have to only deal with interfaces. It can be connect instances of relatively small classes; labelling these connected classes 'Services' and 'Clients' and having to define an interface to define the API of the client, especially if there is only one class that ever implements this interface, may be (in my opinion) overkill in some situations.

    Injection into a constructor can be highly useful in some situations. There may be additional logic triggered by the setting of a bean property and that logic may require other properties to already be in a valid state. (This might be the case if the bean is involved with persistence). The order in which setters are called can't be defined by the bean, but obviously the constructor is called first, so that the properties that must be valid can be injected there.
  44. Ioc and Testing in Isolation
  45. I don't get why pico container and several others IoCCs use component interface as a service(component) identifier. In my view several different services(components) may be specified by the same interface, e.g. Runnable. How these frameworks allow to distinguish these kinds of services?

    As far as I understood, Spring is the only container using the alternative approach based on string identifier.

    I think a service should be defined by string identifier and component interface (this could be solved with generics in Spring).

    P.S. For now I'm experienced in Spring only, and have a limited understanding of other ones.

    Regards,
    Theodore Kupolov
  46. String service ids in pico[ Go to top ]

    I don't get why pico container and several others IoCCs use component interface as a service(component) identifier. In my view several different services(components) may be specified by the same interface, e.g. Runnable.

    This is a common misconception. You can use strings (or any other object with proper equality semantics) as the service identifier in Pico:

    pico.registerComponent("someId", someBean);

    With an interface as the key, you can do what Spring calls 'autowiring'. You don't have to manually wire service instances to clients. But this only works if their is one service implementation per interface. Which is often the case, and autowiring is very convenient when it is. But when it's not, you can use different service identifiers (strings). Pico and Spring are essentially the same here.
  47. I don't get why pico container and several others IoCCs use component interface as a service(component) identifier. In my view several different services(components) may be specified by the same interface, e.g. Runnable. How these frameworks allow to distinguish these kinds of services?As far as I understood, Spring is the only container using the alternative approach based on string identifier.I think a service should be defined by string identifier and component interface (this could be solved with generics in Spring).P.S. For now I'm experienced in Spring only, and have a limited understanding of other ones.Regards,Theodore Kupolov

    HiveMind also support multiple services with unique ids but the same service interface. since often, the service id matches the interface name, there are optimizations to allow for this (and to reduce XML configuration clutter).
  48. Dependency Injection is OK. It should be replaced by other technics like AOP, however via DI you can keep it straighforward (not simple for big projects where you have hundreds dependencies).
    I don't understand advantage to use Spring because idea of DI altready turned in Sprint to using Spring proprietary interfaces in your project for everything. Yes I don't have to, but than why I have to include all Spring in my package?
    It's still high risk to use Spring for real projects of average size.
  49. Dependency Injection is OK. It should be replaced by other technics like AOP, however via DI you can keep it straighforward (not simple for big projects where you have hundreds dependencies).

    AOP does not replace dependency injection - they are quite different things. AOP is about adding behaviour to classes, DI is about linking classes together.
    I don't understand advantage to use Spring because idea of DI altready turned in Sprint to using Spring proprietary interfaces in your project for everything.

    If you are just using DI you need hardly use any Spring interfaces in your code at all. After all, the point of this kind of thing is that matters are handled transparently without you having to explicitly code relationships. A couple of lines of code is all that is needed to locate the configuration files and to load a bean. The rest is handled automatically.
    Yes I don't have to, but than why I have to include all Spring in my package?

    You don't have to. Spring is modular. You just include the bits you need.
    It's still high risk to use Spring for real projects of average size.

    Why? BEA disagrees: http://www.theserverside.com/news/thread.tss?thread_id=34875
  50. If you are just using DI you need hardly use any Spring interfaces in your code at all. After all, the point of this kind of thing is that matters are handled transparently without you having to explicitly code relationships. A couple of lines of code is all that is needed to locate the configuration files and to load a bean. The rest is handled automatically.
    Why class is writen a way that he don't know how to instanciate himself correctly?
    You don't have to. Spring is modular. You just include the bits you need.
    31 MB zip. Minimum is spring.jar 1.8 MB. Too mutch bits.
    Why? BEA disagrees: http://www.theserverside.com/news/thread.tss?thread_id=34875
    Bea don't agree. They just provide support for what developers want.
  51. Minimum is spring.jar 1.8 MB
    Incorrect. There are also a number of more fine-grained JARs if you want just certain features. However, most users tend to prefer the deployment simplicity of a single JAR.
  52. Why class is writen a way that he don't know how to instanciate himself correctly?

    It is not about a class instantiating itself, it is about a class having to instantiate other classes that it requires.
    You don't have to. Spring is modular. You just include the bits you need.
    31 MB zip. Minimum is spring.jar 1.8 MB. Too mutch bits.

    Answered elsewhere!
    Why? BEA disagrees: http://www.theserverside.com/news/thread.tss?thread_id=34875
    Bea don't agree. They just provide support for what developers want.
    They aren't going to provide support for something that isn't supportable.
  53. I don't understand advantage to use Spring because idea of DI altready turned in Sprint [sic] to using Spring proprietary interfaces in your project for everything.
    Not true, as Steve already pointed out. Spring is specifically designed to avoid the use of Spring APIs to meet typical--and even quite sophisticated--configuration requirements.
     Yes I don't have to, but than why I have to include all Spring in my package?
    You can (and should) unit test code configured by Spring without using Spring libraries. That's a key value of dependency injection. To be configured by Spring (or a full-featured IoC container in general), code doesn't need to know about Spring. This is particularly important when you consider the huge amount of legacy code that a good IoC container enables you to leverage without rewriting.
    It's still high risk to use Spring for real projects of average size.
    You'd be surprised at the large scale of many projects using Spring. This is a mature, proven technology with many production deployments across the scale of size and complexity. I can't publically name our best references (for obvious reasons--enterprise-class users value confidentiality) but I'd be happy to discuss some offline. My email is not hard to find if you're interested. BEA's decision to partner with Interface21 to provide Spring support would not have happened unless they had surveyed important customers to ask what products they were using or wanting to use.

    Rgds
    Rod
  54. Xwork[ Go to top ]

    The <enabler> part of xwork config seems unnecessary. Plus the fact that your implementation needs to implement that interface, not as 'clean' as the other ones.
  55. HiveMind Descriptor[ Go to top ]

    Using HiveMind 1.1, the descriptor could be abbreviated to:

    <?xml version="1.0"?>
    <module id="com.dnene.ditutorial.hivemind" version="1.0.0" package="com.dnene.ditutorial.common">
      <service-point id="AirlineAgency">
        <create-instance class="impl.SimpleAirlineAgency"/>
      </service-point>
      <service-point id="CabAgency">
        <invoke-factory>
          <construct class="impl.SetterBasedCabAgency"/>
        </invoke-factory>
       </service-point>
       <service-point id="TripPlanner">
        <invoke-factory>
          <construct class="impl.SetterBasedTripPlanner"/>
        </invoke-factory>
       </service-point>
    </module>

    Modules can be associated with a Java package and class names within (or below) that package can be abbreviated. Also, when the service point id matches the interface name, the interface name can be omitted.

    Also, if you think that <invoke-factory> does not add value ... it is present because there are multiple factories in HiveMind (and it is, of course, expandable). The default, as above, does dependency injection (including auto wiring). In many cases, an alternate factory can "brew up" a service implementation directly from a service interface ... this is used for specialized services that, say, implement the GoF Chain-Of-Command pattern.
  56. Good article. Perhaps is this question beyond the scope of the article but what are the benefits of DI versus the Service Locator pattern we are familiar with in J2EE?