Saturday, November 22, 2008

An awful name for a very cute coding toy

Went to DDD at Msoft today - one thing that caught my attention was one catchy little number called "Inversion of control" - that's a really dire name, but underneath it's quite cute.

Basically:
  • you take a system like a NetworkConnector which is built using tightly coupled objects - e.g. it references a NetworkMonitor, a Logger and a WirelessAdapter
  • you rewrite it so that the NetworkConnector is an INetworkConnector, and so it uses an INetworkMonitor, an ILogger and an IWirelessAdapter - you then also add a simple constructor so that an external builder can pass each of these references in,
  • then at runtime you can use an "Inversion of control container" object to completely wire your system together. There are a few implementations around - with one from "the Castle project" being the main one people seem to be using. Basically what happens is in your system construction you write code that looks a bit like:
Container theContainer = new Container();
theContainer.Register(INetworkConnector, typeOf(NetworkConnector));
theContainer.Register(ILogger, typeOf(Logger));
// etc ...

then at any time later you can ask theContainer for an instance of some interface - e.g. an INetworkConnector - and theContainer will then create it and it's dependent objects and wire them together... (to do this it uses a lot of reflection under the covers)

I know it may not sound that exciting, but what it means is that it's really quite easy to soft-code the relationships between classes - decoupling the classes and so making them easier to plug-in - especially useful for things like test harnesses - especially when used with Mock objects which seem to have come a long way since NMock (RhinoMock running inside TestDriven.net looked particularly neat).

No comments:

Post a Comment