Member-only story
The Great Interface, Part 2
Program to the interface instead of the implementation.

I am a clean code pursuer. Throughout the years, I have always been amazed by the usage of the interface. The interface is an essential concept for object-oriented programming (OOP).
This is the second article of the series, through which I write about OOP from the angle of the interface. If you missed Part 1, I suggest you read it first.
In this article, I will focus on how interfaces can be used to achieve several OO design principles and patterns.
Knowing these OO design principles and patterns is very beneficial when you deal with complex software systems. There is no guarantee that you will get the best way to write a piece of code with them, but they usually lead to maintainable and testable software. Alright, let’s get started.
Dependency Inversion Principle
Martin mentioned 5 design principles, known as “SOLID”, in the book “Clean Architecture” [2]. The last principle “D” standards for Dependency Inversion Principle (DIP), which I found very useful to break the dependency cycle. The following is a typical example.
I used to work on a Mobile App that can make VOIP calls, and we would have a component diagram like the one below. According to the Clean Architecture, volatile software that often changes shall depend on what is more stable. The Application is volatile because it’s UI related and would be changed often for continuous improvement of user experience; while the CallSDK is a stable component focusing on the low-level functionality that changes less frequently. As a result, the Application depends on the CallSDK.

Everything is straightforward so far. However, if we need to ask Application to do something from the CallSDK, e.g. get the battery state. Direct thinking might be a component design as below. This will create a dependency cycle and make the Application and the CallSDK highly coupled, which is a very bad practice. The CallSDK should not depend on the Application.