3 ms·
If you do it right, it makes writing automated unit tests (like JUnit) if not easy, at least possible. If you have a Java class whose constructor instantiates
by commandlinefan 9y ago
If you do it right, it makes writing automated unit tests (like JUnit) if not easy, at least possible. If you have a Java class whose constructor instantiates a JDBC connection to a database, you can't write a unit test for that class without having a live database instance for it to connect to. If you have a method call that includes a HTTP invocation to an external REST endpoint, you can't unit test that unless the REST endpoint is up, running and accessible. If you have a function that deletes rows from a database, you can't test it unless the database is not only available, but has the rows that the function is expecting to delete. IoC, if practiced correctly and usefully, "inverts" those parts so that they can be stubbed/mocked out by the unit testing framework. You can also make the case that, practiced correctly, IoC makes it more likely that the code you wrote can be applied to a different, but similar problems (although in my experience this is more theoretical than practical, since "the business" usually asks for things that don't fit into such nice, neat little boxes). The _problem_ with IoC is when it becomes a religion rather than a testability practice. If you're spending extra time doing something, it should at least be worth the time spent on it.