Member-only story
The Great Interface, Part 1
Program to the interface instead of the implementation
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). I am going to write 3 articles to share with you about some of the common usages of the interface, and this is the first one of the series. This first article covers the background and the basics.
Object-oriented programming (OOP) is the mainstream of software development. To become a good OO software engineer, you may have read about SOLID design principles from Robert C. Martin [2] and 24 design patterns from The Gang of Four [3]. There is one thing being the magic behind those OO design principles and patterns, that’s the great interface. I call it “great” because I think the interface was really a great invention to make a lot of best programming practices possible.
What is the interface?
The interface of OOP means a declaration of a type with a set of functions that any implementation of the interface has to follow. In other words, the interface sets the rule that any implementations shall be able to do certain things. Most of the programming languages support the interface, but maybe with different names. For instance, in Java and Kotlin, we use “interface” directly. With C++, we will need to use abstract classes which contain only pure virtual functions; while in Swift, we use “protocol”. I will use Java for the sample code in this article for simplicity.

The above class diagram shows a simple Player
interface, and there are three concrete classes implementing it, namely CDPlayer
, DVDPlayer
and TapePlayer
.
The sample code of the interface and the three classes is shown below. Just to clarify, the functions in this article are only for demonstration purposes, so you may often find that the functions just print something.