tags:

views:

93

answers:

2

I googled and read some good answers/posts on IOC and do understand the overall concept. I have an existing framework (not very well designed) and TDD is an after thought to write some NUNIT test fixtures. Can I use IOC on an existing code base with out changing the existing code base? Or IOC is used when we are designing application from scratch?

+1  A: 

It doesn't have to be from scratch, but obviously you would structure things to allow IOC to be pretty painless if you did,

But it can be patched in.... depending on how decoupled your system is, that may or may not be a big job. Essentially its an object creation pattern, so it only effect the points of creation.... if thats done willy nilly all over the place, then it will take a bit of clean up.

I'd start with getting unit tests in place first. Worry about IOC as a second concern, its not actually needed to do TDD

Keith Nicholas
Dependency injection is not necessarily needed to write tests, but is pretty central to TDD and unit testing in general -- emphasis on "unit." I'd agree that integrating an IoC *container* is a secondary concern, as it is a facility for DI, but some measure of refactoring for testability is probably unavoidable in a codebase designed without regard for DI/IoC.
Jay
I wouldn't quite agree with that. I think thats true for a certain style of application. Generally the type, where you see the most vocal programmers, which is database backed business / web apps. I've found things like embedded apps hardly ever need it (though you could still use it if you really wanted). Generally all you need there is just stubs at the hardware layer.
Keith Nicholas
+2  A: 

I use this technique for converting legacy code to dependency injected beauty:

  • If I create just one object for a class, make it a field and create it in the constructor.
  • If I create more than one object, make a factory for that object and create the factory in the constructor.
  • Put interfaces on the objects (I like the "IDoThisForYou" style as it allows me to understand the roles of classes easily, but whatever works for you).
  • Cascade the constructors - make one constructor new up the objects and pass them into the other by the interface.

Now you can mock and DI the interfaces in your tests. The actual cascade is simple enough that you can get by with inspection. Eventually you'll get to the point where you can use a container and then you'll delete the first constructor; this is an easy first step towards that.

(Don't mock out domain objects with heavy data - it's not worth it.)

Good luck!

Lunivore
+1 for not mocking domain objects
Gutzofter