Wednesday, August 10, 2022

Dependency Injection

 

After many years of practicing dependency injection via many different frameworks (Spring, Guice, Dagger to name a few), I've decided framework based dependency injection is no longer for me. Every framework starts life as a small, lightweight, easy to use DI tool, and slowly over time morphs into some kind of monstrosity.

If it was just me, maybe I could live with this. I could avoid the bad parts, the parts that make code hard to read at 2am in the morning. But it's not just me. Almost nothing significant gets done without a large number of people working on it - and at some point you just can't stop that one 'beautiful to the beholder' feature being used.

Some time later you spot it being used again and try and stop it. But it's hard to argue with 'but it's already used over there, and over there, and even there'. And it's just as hard to clean those up. And so it spreads. Oozing slowly across your code base, infecting other code bases.

But even if I was strong willed enough to fight every one of those fights to the death, until glorious victory, I'd still be using this monster. I'd be consuming it. I'd be forced to keep using the latest versions, because you know there are important security fixes in it. They just happen to come along with yet another dozen attractive, code reducing features. Yet more reasons for folks to argue about using those features.

"But what's the alternative?", you say, "Surely you can't just discard dependency injection? It's so valuable. It's a core design pattern. Heck, the Gang of Four wrote about it.". Fellow traveler - they did not. Some will tell you that's because unit testing wasn't important back then, that it wasn't a thing.

So what did they write about? Why, Strategy, Singleton and Factory method patterns. Combine them and you see something quite similar to Dependency Injection. If you keep these separate, you end up with more or less the same end capabilities, but with (in my opinion) much more readable code. Certainly at 2am in the morning.

So that's what I'm going to do. I'm just going to focus on writing readable code. I'll leave the injection for the addicts.


No comments:

Post a Comment

Dependency Injection

  After many years of practicing dependency injection via many different frameworks (Spring, Guice, Dagger to name a few), I've decided ...