Interfaces

An interface is just an abstraction of expected interactions with some bit of code, sometimes formalized syntactically. Class/function/module APIs are the general case. Before anything else, let’s look at how you might use interfaces:

Interface Use Cases

What are Interfaces?

An interface is simply a description of how a programmer should expect to be able to interact with block of code. Generally this focuses on functions. However, in an object-oriented context, object state may also be considered a part of an interface.

As an alternatve, interfaces could also be called “Abstract API Models”. All programming languages have at least one means of modeling APIs.

The most common form of interface aims at describing how functions should be used. This includes type declarations for function parameters and return values, a staple of many languages. However, such declarations only capture one aspect of a function’s interface. In most languages, regardless of type system, each function is essentially an API wrapping a block of code.

Functions don’t have the interface market cornered, either. Most languages have a means of encapsulating program state, usually as part of an object-oriented type system. When the topic of interfaces comes up, it tends to refer to formal definitions of what functions and attributes an object (and abstractly, it’s type) should provide.

However, in all cases, interfaces are still just specifications of how one should interact with a block of code.

More references:

Abstract API Model Approaches

To the extent that interfaces are a means of definining expected interactions, they can be approached in a variety of ways. This bears out across the many programming languages in the wild today.

Below is a list of several ways interfaces may be done. Each of these is treated more thoroughly in following sections.

  • Classes
  • Interfaces/Protocols
  • Abstract Base Classes
  • Adaptation
  • Multiple-dispatch/Generics
  • Roles
  • Traits
  • Design by Contract

When are Interfaces Appropriate?

class vs. interface

ABC vs. interface

mixins vs. multiple inheritance

inheritance vs. delegation

inheritance vs. composition

Appendices

adaptation
transforming wrappers