Back to TILs

C++ solid

Date: 2023-02-18Last modified: 2023-02-19

Table of contents

SOLID Principles

Single Responsibility Principle

A class should have only one reason to change

Before:

class Notes {
 public:
  void Add() {}
  void Remove() {}
  void Display() {}
};

After

class Notes {
 public:
  void Add() {}
  void Remove() {}
};

Trasfer the responsability to display Notes to view class

class View {
 public:
  void Display(Notes *notes) {
     // implementation
  }
};

Open-Closed Principle

Modules should be open for extension but closed for modification

This principle explains why we should write software in such a way that its behavior can be modified in future without changing existing code.

Liskov-Substitution Principle

Subtypes must be substitutable for their base types

Learn how inheritance should be used correctly through the Liskov

Interface Segregation Principle

Clients should not be forced to depend on methods they do not use

This principle deals with fat interfaces.

Before:

struct IFile {
  virtual void Read() = 0;
  virtual void Write() = 0;
  virtual ~IFile() = default;
};

After:

struct IRead {
  virtual void Read() = 0;
  virtual ~IRead() = default;
};
struct IWrite {
  virtual void Write() = 0;
  virtual ~IWrite() = default;
};

Dependency Inversion Principle

Abstractions should not depend on details. Details should depend on

A very important principle that forms the flexible structure of all class

Before:

class ImageReader {
 public:
  virtual void Decode() = 0;
  virtual ~ImageReader() = default;
};
class BitmapReader : public ImageReader {
 public:
  void Decode();
};
class ImageViewer {
  BitmapReader *m_Reader{}; // depends on concrete class

 public:
  void Display() {}
};

After

class ImageViewer {
  ImageReader *m_Reader{}; // depends on interface

 public:
  void Display() {}
};

Possible output


References