But Then There Is Also Unnecessary Coupling

August 18, 2008 – 21:05 | misc | Tags:

Jeffrey Palermo writes an interesting post about Inversion of Control is NOT about testability. I guess this is one of the scenarios where I agree with the conclusion, but not necessarily how it is arrived at. :)

Jeffrey drives to his point by giving an example:

C#:
  1. public class MissileLauncher{
  2.     private INavigator _navigator;
  3.     public MissileLauncher(){
  4.         _navigator = new MissileNavigator();
  5.     }
  6.     public void Launch(){
  7.         //get direction guidance from _navigator and launch a missile
  8.     }
  9. }

And then he states:

"This can be a good design or bad design depending on your needs. We are coupling to an interface, INavigator, but we are also coupling to a specific implementation class, MissileNavigator.

"If MissileLauncher can't do its job without MissileNavigator, then this coupling makes sense, and the class should be tested together with MissileNavigator.

Well, I am not sure about that. Looks to me, the commitment of coupling is already made right on the second line of the code above: where _navigator is declared INavigator. It essentially asserts that:

  1. The interface exposed via INavigator suffices for MissleNavigator.
  2. MissileNavigator makes no further assumptions on the class that actually implements INavigator.

Once that commitment is made, specifically instantiating _navigator to an implementation class buys us absolutely nothing, and loses for us most of the flexibility associated from programing against INavigator the interface. Think about it this way, if MissileLauncher has to use the specific implementation, MissleNavigator, meaning at some point it will have to explicitly cast _navigator to MissleNavigator, then that would be a very awkward OO design, and we might as well declare _navigator a MissleNavigator, and program against that interface to begin with.

So, depending on how people look at it, the hard-coded instantiation in the constructor can be considered part of the design or the implementation. But either way IMHO it's a bad one, and makes some unnecessary coupling.

Trackback from your site, or follow the comments in RSS.
  1. 1 Trackback(s)

  2. Oct 12, 2008: Recent Links Tagged With "coupling" - JabberTags

Post a Comment