3

What do they mean with Dependency Injection (Inversion of Control) in this context (Google Mock):

Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, Turtle) and code to that interface:

class Turtle {
  ...
  virtual ~Turtle() {}
  virtual void PenUp() = 0;
  virtual void PenDown() = 0;
  virtual void Forward(int distance) = 0;
  virtual void Turn(int degrees) = 0;
  virtual void GoTo(int x, int y) = 0;
  virtual int GetX() const = 0;
  virtual int GetY() const = 0;
};

What does it have to do with DI when adding another layer between application code and drawing API by a class? In many Java example about Dependency Injection, usually an object should not be concretely created inside a class. Rather, it should be created elsewhere to separate the implementation coupling between two objects. For example (source from codeproject):

enter image description here

Solution:

enter image description here

As I searched through the answers about DI on Stackoverflow, usually it is asked in the context of Java. Some example used the Java GUI. Usually the examples is so simple and so obvious that I failed to see its significance, except for having better design with less coupling. However, what I want to learn is the meaning behind it. As defined in wiki, Inversion of Control (IoC) means you invert the flow of control of code. So, how does it apply to the Google case? How the actual flow is inverted compare to procedural style? I thought that code is executed sequentially line by line from top to bottom, not from bottom to top?

4 Answers 4

3

Wikipedia has good definitions of these:

  1. http://en.wikipedia.org/wiki/Inversion_of_control
  2. http://en.wikipedia.org/wiki/Dependency_injection

Dependency Injection is just a fancy way of saying that the class interacts with another via an interface (the Graphics API) and that it provides a way of changing what the interface points to (i.e. injecting a dependency on another class).

For Inversion of Control, Wikipedia mentions things like the Factory pattern.

It also mentions setter injection (changing an interface implementation using a setter function), construction injection (setting the interface implementation from the constructor) or interface injection (requesting an interface implementation from another interface) and notes that these are types of Dependency Injection.

This is what is happening here -- the program can change the drawing API of the turtle program (Dependency Injection) using a setter method (Inversion of Control).

This allows you to have a test class like this:

struct DrawingTester : public DrawingInterface
{
    void move_to(long x, long y) { printf("moveto %d %d\n", x, y); }
    void line_to(long x, long y) { printf("lineto %d %d\n", x, y); }
};

and drive it through a test program:

int main(int argc, char **argv) {
    DrawingTester drawing;
    Turtle t;
    t.setDrawingApi(&drawing);
    t.runProgramFromFile(argv[0]);
    return 0;
}

You can then have the turtle/logo test programs with expected output from the DrawingTester. For example:

# test1.logo

MOVE 5, 7

# test1.calls

moveto 5 7

and drive this through a test suite (e.g. https://github.com/rhdunn/cainteoir-engine/blob/master/tests/harness.py and https://github.com/rhdunn/cainteoir-engine/blob/master/tests/metadata.py).

2
  • +1, but your example would be even better by not using printf, but storing the commands in a list and showing how to check for the expected results in a real unit test.
    – Doc Brown
    Dec 30, 2011 at 12:16
  • @DocBrown that is possible, however I prefer the approach I mentioned as: (1) it separates the test code from the test data, making it easier for none coders to add and understand the tests; (2) it is easier to maintain; (3) you can use it to examine problem source files that do not have test cases. Point (3) has been very useful for me with my own project.
    – reece
    Jan 1, 2012 at 13:32
3

DI means here, that your program does not have a hardcoded dependency to the LOGO-like api, but this dependency is "injected" at run time through the interface. This way, one can replace the api by a Mock API for purposes of unit testing.

"Inversion of Control" means here: if there is a function in your program needing something like a "graphics context object" of the LOGO-like API, it should not instantiate that object by itself. Instead, it should get the context object given as a parameter (typed to the "Turtle" interface), and the object creation can be done, for example, by the IoC framework.

That will work the same way as you have shown in your "customer-address" example above, replace clsAddress by clsGraphicsContext.

9
  • Thanks. I understand the not instantiate object by itself, as many more example, which leads to the Factory Pattern. However, I have a question here: What do you mean by "your program does not have a hardcoded dependency to the LOGO-like api"? It sounds to me that application should always be protected from external API, by adding our own wrapper class like Turtle. And by not hardcoded, it means instead of calling LOGO-like API in our program (and the API later could be changed), we add another layer which is Turtle, to not break our program?
    – Amumu
    Dec 30, 2011 at 10:00
  • 1
    The API (Turtle in this case) defines the interface/contract between the class/method and your program (e.g. ParseLogo(file, turtle)). This allows your program to define how it responds to the interface events, so the class/method does not have to allowing it to be reused. The program does have a hard-coded dependency on the interface (contract) but the concrete implementation is injected in. If the logo file parser also does the drawing, it is restricted to just that while the interface version is not.
    – reece
    Dec 30, 2011 at 10:21
  • 1
    @Amumu: the primary purpose of the Turtle API is unit testing, not decoupling agains API changes. Your mock graphics context can check if it gets the expected API calls from the part of the program which is the "object-under-test". In a situation where you elsewhere could only check the results of a test by some fragile bitmap comparison an additional layer makes sense. If your LOGO api provides own mechanisms suitable for testing (for example, a custom graphix context object, which can be implemented by you), then there is no need for the "Turtle" layer.
    – Doc Brown
    Dec 30, 2011 at 10:21
  • 1
    It all depends on what you are trying to achieve. A turtle API like in the example is of limited use (requires knowledge of how to process some turtle commands). If you define the API as drawing primitives (move_to/line_to/set_pen_color/...) that allows you to support drawing to screen, bitmap file, scalable vector graphics file, windows meta file sharing the turtle logic, in addition to testing. It also allows you to reuse the drawing interface and handlers for other drawing algorithms. Think about how the API is being used when creating it.
    – reece
    Dec 30, 2011 at 10:37
  • 1
    @Amumu ParseLogo is the method, Turtle is the contract (interface). This allows the caller of ParseLogo to pass their own implementation of the interface -- in this case, to support testing (see my answer for how this can be done). The ParseLogo function can be reused to support drawing to things other than the screen. If ParseLogo did the drawing directly, you could not reuse it to draw to a windows metafile for example, or a different platform (i.e. there could be a WinTurtle, LinuxTurtle and MacTurtle implementation to draw on those platforms).
    – reece
    Dec 30, 2011 at 11:36
2

The inversion in "Inversion of Control" is not an inversion in the order of the code execution, but on object creation. In a architecture that does not use "Dependency Injection", the objects will create their dependencies themselves. On the contrary, when using DI, the object will receive their dependency from the outside, and use interface (abstract class in C++) to get independence from the implementation.

In the LOGO example, by using an interface and a setter instead of creating the API wrapper directly, you allow the code that call you to supply its implementation of the interface. That way, it is easier to test your code (by providing a mocking implementation that record all the call made) or to use another implementation.

1

It seems to me that you are kind of "equating" dependency injection and inversion of control.

Now, as far as I understand, dependency injection is a design pattern (roughly speaking) where you "injects" a pointer to an object into another object; this will make the second dependent on the first (i.e., it needs to know the former's interface, and will be affected by changes at is interface level). So, it is pretty a generic concept that can help in many different context.

In this sense, dependency injection is just a way to implement inversion of control. This happens, for example, when you inject callbacks into an object, so that they are called at the proper moment.

In your specific example, I doubt that dependency injection is used as a way to get inversion of control, since it does not seem to me that control is inverted (like it happens, e.g., when you have callbacks or with frameworks).

It is more a case, as you correctly say, of adding an intermediate layer for better decoupling (which can also be obtained through dependency injection).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.