Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When not to use IoC and DI? [closed]

I see lots of articles saying how great IoC and DI are and none about why it isn't so great because it can make code more complex. I see also that IoC shouldn't be in the core part of your code but more for libraries and plug-ins. Articles usually a small reference to how the two patterns can make code more complicated but not much on the details of that. That is my question - where specifically should you not use these patterns?

This is a nice thread: What is Inversion of Control?. If you look further down, there is a post about the spell checker and another post about how IoC is probably not a good use there if it is only one spell checker. As a general guideline, should IoC not be used of I ever have only one concrete class for the interface? Meaning, I have IMyClass. And then have just the concrete MyClassA that implements IMyClass. Why would I want IoC there?

If I had MyClassA, MyClassB and MyClassC, that each implement IMyClass, those are probably good candidates for IoC correct?

From the same thread, does anyone know what this post means:

  • Inversion of Control = Marriage
  • IOC Container = Wife
like image 418
4thSpace Avatar asked Sep 01 '09 15:09

4thSpace


1 Answers

About your question about having only one interface implementation. When you use IoC, it is still useful to use an interface. It will be much easier to create real unit tests (that doesn't depend on the interface implementation to be working correctly) using mocks for these interfaces. The core of using IoC is making code easier to test. So, don't use IoC if you don't want to test, or already have a better plan on testing without it.

IMHO, DI and IoC increase in complexity comes is paid by having an easier to test and less coupled code. It's easier to isolate the problems and to make future changes. You can control its behavior better too.

I can see when not to use an IoC container (as it results in configuration overhead). This would happen on small projects, where you can do it manually, instead of using a container. But I can't see much loss from using DI, unless you're not planning to test your code...

like image 99
Samuel Carrijo Avatar answered Oct 04 '22 15:10

Samuel Carrijo