Resisting Dependency Injection

How to write code that makes dependency injection more difficult than it needs to be:

  • Use lots of static calls – There’s nothing like a global function or global state that makes it difficult for people to change something. Nested static calls are even better forcing lifecycle choices across the entire application. Who doesn’t want to connect to a database as soon as you load a small part of your application?
  • "New" up instances whenever you need it – Don’t worry about if objects need the same dependencies but earlier in the application… you can create new intances of them as well! Injecting different behaviour? No way!
  • Tie yourself to concrete implementations – Objects don’t have roles. They do stuff and we want that stuff done now. Why would someone want to change the way things are done in the future?
  • ServiceLocate Everything – A variant of the static method. We can use the Service Locator to pull in anything we may happen to need. Layers in an application. Forget it.
  • Pass newly created objects into other objects – Nesting the creation of new objects makes it even harder to unwind at a later stage. You want to inject something into that class? It’ll only need to be passed twelve layers deep!

Comments

  1. June 16th, 2009 | 12:40 am

    Hey Pat…
    Well done.. I totally agree with them… If only everyone thought like this… hehehee
    I saw that you are doing some great stuff with my friend Danilo Sato … well done guys…
    I’m also trying to make some noise in the land down under here… You are from here, right?
    cheers,

  2. June 16th, 2009 | 1:32 am

    [...] It’s been a while since I’ve posted, nothing of interest to say I guess. But then I ran across this article out on Planet TW RSS feed entitled “Resisting Dependency Injection“. [...]

  3. June 17th, 2009 | 9:44 am

    This post would warrant an equivalent “what to do” in response to each “what not to do” bullet. Agree with your points though.

  4. June 18th, 2009 | 7:38 am

    Good point. I’ll add it to my to-do list.

  5. June 22nd, 2009 | 12:18 pm

    [...] one of my previous posts, I wrote about ways that you can make life difficult when injecting dependencies. I find that systems where it is difficult to inject dependencies will be harder to change, will be [...]

  6. June 29th, 2009 | 3:00 am

    [...] Resisting Dependency Injection & Reducing Resistence to Dependency Injection Shows how implementing DI in code can be made harder, and how to make it easier. [...]

Leave a reply