I must be one of the last developers on this planet not to understand
Inversion of Control. Every once in a while, a new tutorial appears, I
think to myself "ok, this is it, this time, I’m really going to understand how I
can use it in all my projects", but every time, I finish the article shaking my
head in utter confusion.
But I still don’t get it.
In this article, the author is using the example of a flight/cab reservation,
which seems reasonable to me. He contrasts the traditional Java approach
to the one used in, say, Spring, where the classes to instantiate are declared
in an XML file.
I have several problems with this approach:
- If you rename one of your classes, you need to remember to update the
XML file as well (as far as I know, no IDE will refactor across non-Java
files as of today).
- If you used interfaces to start with, the odds that you will have to
rename signatures in your API are minimal, so you are better off using
straight Java for this in the first place.
- What is the big gain in Spring invoking my setters instead of me doing
it in plain Java?
- If several instances of the same class need to exist at runtime, I need
to add some sort of XML primary key to my object declarations so that the
container know exactly which instance I need. Tell me again: why am I
writing this in XML instead of Java?
Basically, what you are doing here is spreading your business logic into both
Java and XML for no apparent reason and some quite obvious drawbacks.
Having said that, while I obviously dislike the "setter injection" part of
IoC containers, I do see some value in the factory aspect.
I have found myself reinventing abstract factories way too often and, I bet,
writing bogus implementations many times. It’s not always easy to create a
clean and thread-safe abstract factory implementation, so I definitely see the
point in a framework helping me to specify these in a declarative way and that
would take care of managing the pool of objects, their cardinalities, etc…
PicoContainer does away with XML and writes everything in Java, which makes
more sense to me, and except for the incomprehensible requirement that all your
dependencies need to be declared in the constructor (a constraint the creators
eventually relaxed after years of pressure coming from the community), it seems
to be doing a reasonable job. It’s amazing that it took so long for the
creators to understand that this inane and bigoted requirement made
PicoContainer inapplicable for any kind of pooling
For a more critical and colorful take on PicoContainer, see
Hani’s recent post.
I won’t discuss the XWork section of that article since it seems to me XWork
is much more than just an IoC container so using it for just this purpose would
be very overkill.
Overall, I am still baffled about the excitement around these containers, and
I’m beginning to think that they are actually only used by a small minority of
very, very vocal people…