3 ms·
Testability isn't the only good thing about dependency injection. It's much easier to reason about OO code when objects only tend to interact with objects that
by h2s 14y ago
Testability isn't the only good thing about dependency injection. It's much easier to reason about OO code when objects only tend to interact with objects that they have been explicitly given. Too much willingness to introduce static dependencies increases the risk of creating classes with too many collaborators and/or responsibilities. This is a good example of how a testable design is often also a just plain good design.
Sure, the given examples of "Time.now" or "new Date" are innocuous and I agree that it's a good thing that Ruby allows us to write this type of code without creating a testability issue. But too many people abuse static dependencies for things like database connections which are:
1. well-suited to being represented as proper objects that are passed around
2. better off confined to a small area of the codebase
This is a complex issue and there's a delicate balance that needs to be struck. Otherwise you can end up with a codebase where a few classes are all up in everyone else's shit. That's when you find yourself in embarrassing situations such as some code not working without a database connection even though there's no real need for that beyond the tangled web of static dependencies chaining it to the database class.