CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 5 of 6 · 2 min read

Why inversion

The arrow flips.

Why it is called inversion

In the first version, the arrow of dependence points from the important class to the detail: BookingService to SmtpSender. The flow of control goes the same way, since the service calls the sender.

In the second version, the service points to the Notifier interface. The SmtpNotifier also points to the interface, because it implements it. The arrow from the detail now points up toward the important code. The control still flows from the service to the detail at run time, but the source code dependencies run the other way. CA draws a curved line between the abstract side and the concrete side, and notes that all the arrows across it point toward the abstract side. That reversal against the flow of control is the "inversion".

CA also gives four coding habits that follow from the rule.

  • Do not refer to volatile concrete classes. Refer to interfaces. This also limits how objects are created, which often calls for the abstract factory pattern (module 2 of Level 3).
  • Do not subclass volatile concrete classes. Inheritance is the strongest and least flexible tie in a typed language.
  • Do not override concrete methods. An override keeps the dependencies of the code it replaces. Make the method abstract and write several implementations.
  • Do not name anything concrete and volatile. This is the rule again in different words.

Common mistake

Writing an interface for every class, even stable ones such as String or a plain data holder. Put interfaces at the points where details are likely to change, such as email, payment, storage and time.

Interview angle

Answer in your head first, then open it.

What is dependency inversion?

High-level code depends on an interface, and low-level details implement it, so the source arrows point toward the abstraction.

How do you apply it in Java?

Define an interface owned by the high-level code, and pass an implementation in through the constructor.

What does it buy you?

Details can be swapped without editing the service, and tests can use fakes.

Check yourself: 1. In the second version, which way does the arrow from SmtpNotifier point? 2. Why is overriding a concrete method a hidden dependency?

Words you will meet

Word Meaning
Abstraction An interface or abstract class that hides details
Concrete class A class with real behaviour, not an interface
Volatile Changes often, because the team is still working on it
Injection Passing a dependency in from outside, usually by constructor
Fake A simple stand-in class used in tests