Dependency Injection Isn’t Only an OOP Concept

August 31, 2013

Dependency Injection (DI) is a very important concept in software engineering. It has even received the status of a “design pattern“, with all the bells and whistles of the field.

The principle behind DI is that software layers can be decoupled in more flexible ways. Inverting control between callers/callees, it’s possible to improve code reusability, testability, and maintainability.

James Shore provided a very insightful treatment for the subject, depicting DI as a simpler concept than what is usually found on literature. Going one step further, it’s not difficult to realize that DI isn’t only about Object-Oriented Programming (OOP). And this is so, not because it’s possible to express OOP techniques in plain procedural code (with higher-level constructs’ emulation).

In fact, plain “old” C has supported DI for decades! Let’s consider qsort(). A callback is “injected” (passed) by callers of this routine, taking the control of the sorting process away from the inner callee logic. The simple act of exposing the comparison dependency makes qsort() useful in broader scenarios.

Function pointers are an idiomatic way of implementing DI in C. And although this type of indirection has a cost, it’s the price to be paid for more generic implementations, applicable in many more contexts.