DI frameworks like Guice and Spring are the common tools to abstract out dependencies to make Java code testable. However, there are several alternate methods to achieve the same goals. One in particular is making the code to test depend directly on certain classes and then varying which implementations of those classes are in the classpath at test and run time, as SLF4J does.

Are there compelling reasons to use DI frameworks instead of the classpath to control dependencies? If not, why is the latter approach not more common given that it is simpler and uses only built-in functionality?

  • It will sound like a cop out answer, but using standard DI frameworks is the industry standard and it works. You're not writing code for yourself; you're writing it for future developers. Following the status quo when the status quo doesn't work is bad. Following the status quo when it works fine and you gain nothing from deviating is going to create a maintenance headache down the line. Aug 26 '16 at 22:15
  • Classpath-based abstraction is not possible if you ever need more than one implementation of something in the same program. Additionally you'd need to move every single class you want to swap this way into a separate jar.
    – Doval
    Aug 26 '16 at 23:01
  • @christopher Frankly, anyone who would hesitate to understand either approach to DI would have no chance to understand the algorithms being written, and so that person would have no business touching the library. Aug 28 '16 at 1:04
  • Your frankness is accepted and noted. Your arguments are valid. Aug 28 '16 at 1:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.