What does it mean to program to an interface?

Viewed 6939

I keep hearing the statement on most programming related sites:

Program to an interface and not to an Implementation

However I don't understand the implications?
Examples would help.

EDIT: I have received a lot of good answers even so could you'll supplement it with some snippets of code for a better understanding of the subject. Thanks!

17 Answers

Coding to an interface is a philosophy, rather than specific language constructs or design patterns - it instructs you what is the correct order of steps to follow in order to create better software systems (e.g. more resilient, more testable, more scalable, more extendible, and other nice traits).

What it actually means is:

===

Before jumping to implementations and coding (the HOW) - think of the WHAT:

  • What black boxes should make up your system,
  • What is each box' responsibility,
  • What are the ways each "client" (that is, one of those other boxes, 3rd party "boxes", or even humans) should communicate with it (the API of each box).

After you figure the above, go ahead and implement those boxes (the HOW).

Thinking first of what a box' is and what its API, leads the developer to distil the box' responsibility, and to mark for himself and future developers the difference between what is its exposed details ("API") and it's hidden details ("implementation details"), which is a very important differentiation to have.

One immediate and easily noticeable gain is the team can then change and improve implementations without affecting the general architecture. It also makes the system MUCH more testable (it goes well with the TDD approach).

===
Beyond the traits I've mentioned above, you also save A LOT OF TIME going this direction.

Micro Services and DDD, when done right, are great examples of "Coding to an interface", however the concept wins in every pattern from monoliths to "serverless", from BE to FE, from OOP to functional, etc....

I strongly recommend this approach for Software Engineering (and I basically believe it makes total sense in other fields as well).

Related