Dependency Injection Bad Practices

Let’s cover some common DI antipatterns.

Luís Soares
CodeX

--

Image by Jp Valery via Unsplash Copyright-free

Before moving on, make sure you read the basics:

Instantiating dependencies in the components

Instantiating dependencies directly in components where needed is the opposite of DI. Hidden dependencies make code work like magic, and you never know what depends on what. This is the worst antipattern because it’s hard to track where a network or database call is made. It’s not a DI antipattern because you’re not using it, but it’s DI-related.

// ⛔
class SimulateLoan() {
operator fun invoke() {
val taxCalculator = TaxCalculator()
...
}
}️

A standard solution is to make the components access a broad scope (e.g., a global function or singleton), but that makes refactoring painful and testing very hard (the monkey patching hell).

📝 If you feel the need to monkey patch things while testing (e.g., Python’s @Patch, Jest’s module mocking, Rails monkey patching), then you have a hidden

--

--

Luís Soares
CodeX

I write about automated testing, Lean, TDD, CI/CD, trunk-based dev., user-centric dev, domain-centric arch, ...