liveBook · Manning

Code to the interface principle

As explained in Object-Oriented Software Design in C++

A design principle that makes code depend on an interface and polymorphic behavior rather than a specific subclass implementation.

Code to the Interface means depending on a superclass interface instead of a specific subclass implementation. This lets one variable work with multiple subclasses through polymorphism. section 2.3.3

Shapes: replace a concrete dependency

A Rectangle pointer can call display(), but it works only with Rectangle. Replacing it with Shape* allows the same code to point to Rectangle or Circle; the runtime object determines which display() implementation runs.

Apply the principle by moving shared dependencies to the superclass interface:

  • Store an Attributes* in Book rather than a FictionAttrs* or CookbookAttrs*; subclasses inherit changes to coordinate their behavior without code modification. section 2.3.3
  • Store vector<Book*> in Catalogue so the collection can contain different book subclasses instead of depending on one concrete type. section 2.3.3
  • Use polymorphic operations when behavior must vary at runtime; avoid unnecessary subclasses, runtime type checks, and type conversions that increase complexity. section 2.4

How Object-Oriented Software Design in C++ covers it

How deep it goes
Defines the principle and demonstrates refactoring with shapes and books, but stops short of a general implementation checklist.
Examples
Demonstrates Shape with Rectangle and Circle, then Book with Fiction, Cookbook, and their attribute subclasses.
What it assumes
Assumes basic classes and subclasses while introducing interfaces, polymorphism, runtime dispatch, and dynamic casting through examples.
What you can do after
Evaluate designs for concrete-subclass coupling and apply polymorphic superclass interfaces to support multiple subclasses.
How it connects
Connects polymorphism with inheritance, encapsulation, loose coupling, and the Open-Closed Principle.

Also explained in

Compare how 2 books explain code to the interface principle →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.