Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
Home/C++/SOLID
C++

C++

Zero-cost abstractions and full control over memory.

Paradigm
Multi-paradigm, OOP, generic
Typing
Static, strong-ish
Memory
Manual / RAII, no GC
Runs
Native machine code (AOT)
Concurrency
Threads, atomics, coroutines (C++20)

SOLID principles

Five principles that make object-oriented designs easier to understand, change and maintain. The text is adapted from the training-algorithms repositories' README.

S  Single Responsibility principle

“There should never be more than one reason for a class to change.”

  • A class should only have one reason to change
  • Separation of concerns
  • Different classes handle different, independent tasks
Diary
  • addNote(note)
  • removeNote(pos)
  • saveToFile(name)
  • loadFromFile(name)
PersistenceManager
  • saveToFile(diary, name)
  • loadFromFile(name)

Two reasons to change: note rules and file storage live in one class.

The repository splits a Diary (manages notes) from a PersistenceManager (saves and loads them):

training-algorithms-c/SOLID/SingleResponsiblityPrinciple.cpp (excerpt)
// Diary only manages notes. Its single reason to change: note rules.
class Diary {
public:
    void addNote(const std::string &note) {
        count++;
        notes.push_back(std::to_string(count) + ": " + note);
    }
    void removeNote(int pos);
    friend std::ostream &operator<<(std::ostream &os, const Diary &diary);
private:
    std::vector<std::string> notes;
    int count = 0;
};

// Persistence lives elsewhere. Its reason to change: storage format.
class PersistenceManager {
public:
    static void saveToFile(const Diary &diary, const std::string &filename);
    static Diary loadFromFile(const std::string &filename);
};

O  Open–Closed principle

“Software entities should be open for extension, but closed for modification.”

  • Add behaviour by adding new code (subclasses, strategies), not by editing tested code

A code example for this principle is coming soon.

L  Liskov Substitution principle

“Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.”

  • You should be able to substitute a base type with a subtype

A code example for this principle is coming soon.

I  Interface Segregation principle

“Clients should not be forced to depend upon interfaces that they do not use.”

  • Don't put too much into an interface; split it into separate interfaces
  • YAGNI: You Aren't Gonna Need It

A code example for this principle is coming soon.

D  Dependency Inversion principle

“Depend upon abstractions, not concretions.”

  • High-level modules should not depend on low-level ones; both use abstractions

A code example for this principle is coming soon.

Saved in this browser only. Part of Clean code foundations (0/5).