Garo Garabedyan's Divergent Thinking Blog

Handling Dependency Injection in C

leave a comment »

Martin Fowler, Inversion of Control Containers and the Dependency Injection pattern, 2004 has proposed the concept of Dependency Injection. Despite the fact that Inversion of Control or more accurately termed Dependency Injection is explained in Object-Oriented paradigms (dependencies between classes), I believe that dependency injection can be as well used in non-OO (i.e. C) programs as in OO.

Inversion of Control (IoC) in procedures and functions in procedural programming languages can give big flexibility and re-usability of the code. Handling dependency injection in such a way to propose as few as possible code rewriting in result of updates in a reasonable price of code readability and powerful procedure and function white-box testing. Handling dependency injection will improve Single Responsibility Principle (SRP)-give each function/procedure (class in OOP) just one reason to change; and “Reason to change” == “responsibility”.

Handling dependency injection is proposed here by presenting each and every global variable and function/procedure call in the list of arguments of the concrete function/procedure.

Example (used The Function Pointer Tutorials):

// Pointer to global function. Using TYPEDEF is not a requirement.
typedef int (*ptXFunction) ();

int globalFunc () {
 // code ;

void func (/* arguments */, ptXFunction globalFunc = &globalFunc) {
 // code ;
 // calling the global function int globalFunc () through its local function pointer globalFunc

Written by garabedyan

May 25, 2009 at 16:40

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