Dependency Injection Part V: When to use (or not)

Previously we looked at Dependency Injection in detail, looking at the advantages and disadvantages in detail, and examining ways to overcome some of the disadvantages. I’d like to summarize by exploring when to use it and when not to use it.

In general it would be a good idea to use DI when the advantages outweigh the disadvantages, or the disadvantages can be mitigated. A careful review of the advantages and disadvantages we’ve already discussed might point you in the right direction. We don’t have hard and fast rules to say “use it here” and “don’t use it there”, we really need to investigate the pros and cons and see how the apply to what we’re trying to build. The decision is an architectural one and generally needs to be made early in the design of an application.

As a rule of thumb however, using a DI container could be a good choice at the very least if you are starting a project and want a standard technique to compose subsystems and orchestrate the large scale construction. This is another advantage that I didn’t mention before, but many of the large scale structures in an application are singletons, and DI containers facilitate a solution to the Singleton anti-pattern. Rather than controlling singleton instantiation yourself (which is easy to get wrong, common solutions include double-checked locking or enum singletons) the container controls the instantiation of a singleton.

As another rule of thumb, there are times when DI might not be a good choice. If you are working with a large legacy system that does not use DI at all, it could be prohibitively expensive to bolt on. DI is high-level and is best introduced at design time. Java lang objects that really are implementation details, such as Lists and Maps should probably not be injected. And objects created late in the scope’s lifecycle should be not injected (or the scope of the object should be rethought). Finally, if your project is a library or a small application, the overhead of using a framework (indeed, any framework, not just a DI framework) tips the scale in favor of not using it. For software in general it’s good to keep things as simple as possible for as long as possible.

Leave a comment

Filed under Software Engineering

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s