Saturday, March 12, 2011

PicoContainer Auto-Wiring and type safety.

One of the things that people often criticize (unjustly, I might add) about PicoContainer is that it recommends Auto-wiring wherever possible: When an object is constructed, PicoContainer searches for the best possibility to serve as its dependencies.
Chariot Framework and in particular, the front controller, Chariot Command relies heavily on PicoContainer autowiring, because even though you can use Pico’s ‘parameter’ ability to specify constructors, method argument matching is impossible if it isn’t autowireable. 
(Note, this original post was written before javax.inject annotations became available – however, I still haven’t gotten hugely into the annotation markup.)
But it has had an interesting side effect:
Instead of having all sorts of HashMaps scattered around the code base, I have been creating lots of little maps that derive from AbstractMap. One map for each type of ‘map’. Examples in Genesis Command are:
RequestAttributeMap
SessionMap
ParameterSource
None of these classes have been hard to create – in fact, they’re pretty simplistic. But it allows me to use autowiring to its fullest capability. (And frankly, I HATE having to use the specific parameters – I avoid them if at all possible.)
The thing that has become clear after using this technique since 2003: it is highly beneficial to code maintenance for a couple of reasons:

1 – The intent of the map is evident by its type, not just the variable name.

I can easily find where this type is being used thanks to IDE searching facilities, and the purpose of those functions that use the type is quite evident.

 

2 – I don’t lose any capabilities

If I need a generic algorithm, I can still use them because each of the above maps still implement the Map interface, so I don’t lose any capabilities there.

 

3 – I can better tie in behavior with the objects.

One day I needed to be able to determine if a ‘command parameter’ was present in the parameters my Web command object was receiving. With the design I had chosen to avoid autowiring, the solution was simple – add the query behavior to ParameterSource.
I had a clean, encapsulated implementation whereas the other way around, most would have used functions to examine the map and decide if a command parameter was present.
So hats off to PicoContainer and its auto-wiring capabilities. My program structures are significantly improving because of it!

No comments:

Post a Comment