Lesson 4
Applying SOLID Principles in C++
Introduction

Welcome to the final lesson of the "Applying Clean Code Principles in C++" course! Throughout this course, we've covered vital principles such as DRY (Don't Repeat Yourself), KISS (Keep It Simple, Stupid), and the Law of Demeter, all of which are foundational to writing clean and efficient code. In this culminating lesson, we'll explore the SOLID Principles, a set of design principles introduced by Robert C. Martin, commonly known as "Uncle Bob." Understanding SOLID is crucial for creating software that is flexible, scalable, and easy to maintain. Let's dive in and explore these principles together.

SOLID Principles at a Glance

To start off, here's a quick overview of the SOLID Principles and their purposes:

  • Single Responsibility Principle (SRP): Each class or module should only have one reason to change, meaning it should have only one job or responsibility.
  • Open/Closed Principle (OCP): Software entities should be open for extension but closed for modification.
  • Liskov Substitution Principle (LSP): Objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program.
  • Interface Segregation Principle (ISP): No client should be forced to depend on methods it does not use.
  • Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions.

These principles are guidelines that help programmers write code that is easier to understand and more flexible to change, leading to cleaner and more maintainable codebases. Let's explore each principle in detail.

Single Responsibility Principle

The Single Responsibility Principle states that each class should have only one reason to change, meaning it should only have one job or responsibility. This helps in reducing the complexity and enhancing the readability and maintainability of the code. Consider the following:

C++
1class User { 2public: 3 void printUserInfo() { 4 // Print user information 5 } 6 7 void storeUserData() { 8 // Store user data in the database 9 } 10};

In the above code, the User class has two responsibilities: printing user information and storing user data. This violates the Single Responsibility Principle by taking on more than one responsibility. Let's refactor:

C++
1class User { 2public: 3 // User-related attributes and methods 4}; 5 6class UserPrinter { 7public: 8 void printUserInfo(const User &user) { 9 // Print user information 10 } 11}; 12 13class UserDataStore { 14public: 15 void storeUserData(const User &user) { 16 // Store user data in the database 17 } 18};

In the refactored code, we have three classes, each handling a specific responsibility. This makes the code cleaner and easier to manage.

Open/Closed Principle

The Open/Closed Principle advises that software entities should be open for extension but closed for modification. This allows for enhancing and extending functionalities without altering existing code, reducing errors and ensuring stable systems. Consider this example:

C++
1class Rectangle { 2public: 3 Rectangle(double width, double height) : width(width), height(height) {} 4 5 double area() const { 6 return width * height; 7 } 8 9private: 10 double width, height; 11}; 12 13class AreaCalculator { 14public: 15 double calculateRectangleArea(const Rectangle& rectangle) const { 16 return rectangle.area(); 17 } 18};

In this setup, if we want to add a new shape like Circle, we need to modify the AreaCalculator class, which violates the Open/Closed Principle. Here is an improved version using polymorphism:

C++
1class Shape { 2public: 3 virtual double area() const = 0; 4 virtual ~Shape() {} 5}; 6 7class Rectangle : public Shape { 8public: 9 Rectangle(double width, double height) : width(width), height(height) {} 10 11 double area() const override { 12 return width * height; 13 } 14 15private: 16 double width, height; 17}; 18 19class Circle : public Shape { 20public: 21 Circle(double radius) : radius(radius) {} 22 23 double area() const override { 24 return 3.14159 * radius * radius; 25 } 26 27private: 28 double radius; 29}; 30 31class AreaCalculator { 32public: 33 double calculateArea(const Shape& shape) const { 34 return shape.area(); 35 } 36};

Now, new shapes can be added without altering AreaCalculator. This setup adheres to the Open/Closed Principle by leaving the existing code unchanged when extending functionalities.

Liskov Substitution Principle

The Liskov Substitution Principle ensures that objects of a subclass should be able to replace objects of a superclass without altering the functionality or causing any errors in the program.

C++
1class Bird { 2public: 3 virtual void fly() { 4 std::cout << "Flying" << std::endl; 5 } 6 7 virtual ~Bird() {} 8}; 9 10class Ostrich : public Bird { 11public: 12 void fly() override { 13 throw std::runtime_error("Ostrich can't fly"); 14 } 15};

Here, substituting an instance of Bird with Ostrich causes an issue because Ostrich cannot fly, leading to an exception. Let's refactor:

C++
1class Bird { 2 // Common behaviors for all birds 3 virtual ~Bird() {} 4}; 5 6class FlyingBird : public Bird { 7public: 8 virtual void fly() { 9 std::cout << "Flying" << std::endl; 10 } 11}; 12 13class Ostrich : public Bird { 14 // Specific behaviors for ostriches 15};

By introducing FlyingBird and having only birds that can actually fly inherit from it, we can substitute Bird with Ostrich without errors, adhering to the Liskov Substitution Principle.

Interface Segregation Principle

The Interface Segregation Principle states that no client should be forced to depend on methods it does not use. Interfaces should be split into smaller, more specific entities so that clients only implement the methods they need:

C++
1class Worker { 2public: 3 virtual void work() = 0; 4 virtual void eat() = 0; 5 virtual ~Worker() {} 6}; 7 8class Robot : public Worker { 9public: 10 void work() override { 11 // Robot work functions 12 } 13 14 void eat() override { 15 // Robots don't eat, but must implement this method 16 } 17};

Robot being forced to implement eat() violates the Interface Segregation Principle. Here's the refactored version:

C++
1class Workable { 2public: 3 virtual void work() = 0; 4 virtual ~Workable() {} 5}; 6 7class Eatable { 8public: 9 virtual void eat() = 0; 10 virtual ~Eatable() {} 11}; 12 13class Robot : public Workable { 14public: 15 void work() override { 16 // Robot work functions 17 } 18};

Now, Robot only implements the Workable interface, adhering to the Interface Segregation Principle.

Dependency Inversion Principle

The Dependency Inversion Principle dictates that high-level modules should not depend on low-level modules, but both should depend on abstractions. Here's an example:

C++
1class LightBulb { 2public: 3 void turnOn() { 4 std::cout << "LightBulb turned on" << std::endl; 5 } 6 7 void turnOff() { 8 std::cout << "LightBulb turned off" << std::endl; 9 } 10}; 11 12class Switch { 13private: 14 LightBulb lightBulb; 15 16public: 17 Switch() : lightBulb() {} 18 19 void operate() { 20 // Operate on the light bulb 21 lightBulb.turnOn(); 22 lightBulb.turnOff(); 23 } 24};

Here, Switch directly depends on LightBulb, making it challenging to extend the system with new devices without modifying Switch. Every time a new device type is introduced, the Switch class would need modification, leading to tight coupling between the Switch and the device.

To adhere to the Dependency Inversion Principle, we introduce an abstraction:

C++
1class Switchable { 2public: 3 virtual void turnOn() = 0; 4 virtual void turnOff() = 0; 5 virtual ~Switchable() {} 6}; 7 8class LightBulb : public Switchable { 9public: 10 void turnOn() override { 11 std::cout << "LightBulb turned on" << std::endl; 12 } 13 14 void turnOff() override { 15 std::cout << "LightBulb turned off" << std::endl; 16 } 17}; 18 19class Switch { 20private: 21 Switchable* client; 22 23public: 24 Switch(Switchable* client) : client(client) {} 25 26 void operate() { 27 // Operate on the switchable client 28 client->turnOn(); 29 client->turnOff(); 30 } 31};

Now Switch uses the Switchable interface, which can be implemented by any switchable device. This setup allows the Switch class to remain unchanged when introducing new devices, thus following the Dependency Inversion Principle by depending on an abstraction and reducing the system's rigidity.

Review and Next Steps

In this lesson, we delved into the SOLID Principles — Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. These principles guide developers to create code that is maintainable, scalable, and easy to extend or modify. As you prepare for the upcoming practice exercises, remember that applying these principles in real-world scenarios will significantly enhance your coding skills and codebase quality. Good luck, and happy coding! 🎓

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.