Wednesday, August 6, 2008

A Crazy Idea about Dependency Injection

At the end of my post yesterday, I mentioned the term Dependency Injection. I can't go into too much detail because it's not a concept I've really been able to work with much... yet. My only real exposure is the Google Guice book.

That's not gonna stop me from diving right in though.

Basically, when you use DI, you never use the new operator which means you never explicitly allocate objects. In a modern programming language (where modern implies garbage collection), this give you quite a bit of flexibility to reconfigure your app without changing your business logic. You just configure which concrete classes are mapped to which interface. For instance, you can remap ICurrency from Dollar to Euro in one place.

What's struck me though is the implications this might have for C++. By taking 'new' out of the program logic, we should be able to abstract away most, if not all, of the manual memory management that is so painful.

Instead of allocating an instance object in the constructor and freeing it in the destructor, we inject an already allocated object into the constructor. It is now the DI container's job to allocate and deallocate that object. Finally, assuming that you have a good enough DI framework (is this like a smart enough compiler?), it should take care of that task for you. You just map types.

Am I crazy?

No comments: