But Then There Is Also Unnecessary Coupling
August 18, 2008 – 21:05 | misc | Tags: designJeffrey 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:
-
public class MissileLauncher{
-
private INavigator _navigator;
-
public MissileLauncher(){
-
}
-
public void Launch(){
-
//get direction guidance from _navigator and launch a missile
-
}
-
}
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:
- The interface exposed via
INavigatorsuffices forMissleNavigator. MissileNavigatormakes no further assumptions on the class that actually implementsINavigator.
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.

1 Trackback(s)