The 5 commandments of clean, maintainable object-oriented design.
psychology Why SOLID?
SOLID principles help software engineers write code that is easy to maintain, understand, and extend.
In C++, where memory management and inheritance complexities abound, adhering to these rules prevents "spaghetti code" and reduces technical debt.
code How to use this app
Select a principle from the sidebar to dive deep.
You'll see visual analogies, clear definitions, and interactive Bad vs Good code comparisons.
Single Responsibility Principle
"A class should have one, and only one, reason to change."
Problem: The User class handles data, database operations, AND email formatting. Changing the DB or email logic requires changing the User class.
"Subtypes must be substitutable for their base types."
Problem: The Classic Square/Rectangle problem. A Square IS-A Rectangle in geometry, but not in behavior. Setting width on a Square changes its height, violating the Rectangle's behavior expectations.
Solution: Separate the hierarchy. Square and Rectangle are both Shapes, but one does not inherit the other's *implementation* details like setWidth/setHeight.
classShape {
public:
virtualintgetArea()= 0;
};
classRectangle : public Shape {
int width, height;
public:
Rectangle(int w, int h) : width(w), height(h) {}
voidsetWidth(int w){ width = w; }
voidsetHeight(int h){ height = h; }
intgetArea()override{ return width * height; }
};
classSquare : public Shape {
int size;
public:
Square(int s) : size(s) {}
voidsetSize(int s){ size = s; }
intgetArea()override{ return size * size; }
};
// Now process() cannot make wrong assumptionsvoidprintArea(Shape& s){
cout << "Area: " << s.getArea() << endl; // Works for both
}
Interface Segregation Principle
"Clients should not be forced to depend on interfaces they do not use."
Problem:IMachine forces a SimplePrinter to implement scan() and fax() even if it can't. This leads to empty methods or runtime errors.