SOLID Principles

Is SOLID Only for OOP?

SOLID uses object-oriented terms, but its core ideas also apply to plain functions and templates in C++. Learn where the ideas fit beyond classes.

On this page
  1. Why SOLID uses object-oriented terms
  2. The same goal without classes
  3. When plain functions are the clearer choice
  4. Summary

SOLID is written in object-oriented terms, so it is closely tied to classes, interfaces and inheritance. The ideas behind it, such as keeping responsibilities separate and depending on stable abstractions, are not limited to classes. You can apply them in C++ code that uses plain functions and templates.

Why SOLID uses object-oriented terms

The five principles talk about classes, subclasses and interfaces. Liskov substitution, for example, asks whether a derived class can stand in for its base class. The open/closed principle is often carried out with virtual functions. That is why SOLID feels most natural in object-oriented code.

The same goal without classes

In C++, you can add behavior without editing a function by passing the behavior in as an argument. The function below accepts any callable that takes an int and returns an int, using std::function:

#include <functional>
#include <iostream>
#include <vector>

int sumWith(const std::vector<int>& values,
            const std::function<int(int)>& transform) {
    int total = 0;
    for (int value : values) {
        total += transform(value);
    }
    return total;
}

int square(int x) {
    return x * x;
}

int doubled(int x) {
    return 2 * x;
}

int main() {
    std::vector<int> numbers{1, 2, 3};
    std::cout << sumWith(numbers, square) << "\n";   // 14
    std::cout << sumWith(numbers, doubled) << "\n";  // 12
}

sumWith does not change when you add a new way to transform the numbers. You write a new function and pass it in. This is the open/closed idea without a class hierarchy. For more on storing and calling functions this way, see c std::function.

Templates offer a similar kind of flexibility, with the types checked at compile time. They are a separate topic, but they are another way to write code that works with many types without editing the original code.

When plain functions are the clearer choice

Procedural or functional code can be clear and correct without classes. A short program that reads a file and prints a total may be easier to follow as a few functions. Adding classes and interfaces to such a program can make it harder to read without any real gain.

Summary

SOLID is a set of object-oriented guidelines, but the goals behind it apply more broadly. Separating concerns and depending on stable interfaces can shape functions and templates too. For a class-based introduction, see solid principles in c, inheritance in c and polymorphism in c.

The complete guide to solid principles

SOLID Principles in C++
Read the guide

Keep exploring

Guides from other topics

All topics →