Mastering SOLID Principles in Modern C++20 with Robotics Examples
As a low-level language user, the terms of SOLID is less-known (or maybe it’s just me that just knew this term these days). But I found out that this terms is prety useful especially for those who works with Object Oriented Programming Languages such as C++, Java, etc.


Introduction
As a low-level language user, the terms of SOLID is less-known (or maybe it’s just me that just knew this term these days). But I found out that this terms is prety useful especially for those who works with Object Oriented Programming Languages such as C++, Java, etc.
What is SOLID Principle?
So, basically, SOLID principle is an acronym for five object-oriented design (OOD) principles by Robert C. Martin (known-well as uncle bob).
These principles provide guidelines for building software that remains maintainable and scalable as the project expands. Implementing them can also help prevent code smells, simplify refactoring, and support the development of Agile or Adaptive software.
““The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.” — Joe Armstrong at Coders at Work by Peter Seibel.”
Yes, OOP could be a double-edged sword, when you play around with it, you need to make sure that you’re safe enough. So it wouldn’t have any problem in the future. That’s why today I wanna talk about SOLID.
What Does SOLID Stands For?
As I said before, SOLID is an acronym. SOLID stands for
S — Single-responsibility Principle O — Open-closed Principle L — Liskov Substitution Principle I — Interface Segregation Principle D — Dependency Inversion Principle
But what does each of them talks about?
Single Responsibility Principle
The Single Responsibility Principle states that:
“A class should have one and only one reason to change, meaning that a class should have only one job.”
Did you feel like you don’t get it? it’s okay, when the first time I hear about this principle, I also had the same issue. So let me just make an example of a bad SRP and good SRP.
In a robotics system, let’s say we have a robot arm controller. A bad design would be a single class handling both motion control and logging, which violates SRP.
Here is the Example that Violates SRP ❌:
1#include <iostream>
2#include <fstream>
3#include <string>
4
5class RobotArm {
6public:
7 void moveTo(double x, double y, double z) {
8 // Simulate movement
9 std::cout << "Moving to position: (" << x << ", " << y << ", " << z << ")\n";
10
11 // Violates SRP: Handles movement AND logging
12 logMovement(x, y, z);
13 }
14
15private:
16 void logMovement(double x, double y, double z) {
17 std::ofstream logFile("robot_movement.log", std::ios::app);
18 if (logFile) {
19 logFile << "Moved to: (" << x << ", " << y << ", " << z << ")\n";
20 } else {
21 std::cerr << "Error writing log file.\n";
22 }
23 }
24};
25
26int main() {
27 RobotArm robot;
28 robot.moveTo(1.0, 2.0, 3.0);
29 return 0;
30}Why is this bad?
- The RobotArm class is responsible for both movement control and logging, violating SRP.
- If we want to change how logs are stored (e.g., send them to a database or ROS topic), we would have to modify Robot Arm, which is unrelated to movement.
Good Example That Follows SRP:
We separate concerns by creating a dedicated class for logging, keeping Robot Arm focused only on movement control.
1#include <iostream>
2#include <fstream>
3#include <string>
4
5// Separate logging class
6class Logger {
7public:
8 static void logMovement(double x, double y, double z) {
9 std::ofstream logFile("robot_movement.log", std::ios::app);
10 if (logFile) {
11 logFile << "Moved to: (" << x << ", " << y << ", " << z << ")\n";
12 } else {
13 std::cerr << "Error writing log file.\n";
14 }
15 }
16};
17
18// RobotArm class ONLY handles movement
19class RobotArm {
20public:
21 void moveTo(double x, double y, double z) {
22 // Simulate movement
23 std::cout << "Moving to position: (" << x << ", " << y << ", " << z << ")\n";
24
25 // Delegates logging responsibility
26 Logger::logMovement(x, y, z);
27 }
28};
29
30// Usage
31int main() {
32 RobotArm robot;
33 robot.moveTo(1.0, 2.0, 3.0);
34 return 0;
35}Why is this better?
- The RobotArm class only controls movement ✅.
- The Logger class only handles logging ✅.
- If we want to change how logs are stored (e.g., send them to a ROS topic or a cloud server), we only modify Logger, leaving RobotArm untouched✅.
Open-Closed Principle
Open-closed Principle (OCP) states:
“Objects or entities should be open for extension but closed for modification.”
This means that we should be able to add new functionality without modifying existing code. Instead of modifying a class when new features are needed, we should extend it through inheritance or polymorphism.
This principle helps in robotics by making software more scalable, maintainable, and less error-prone, especially when adding new robot behaviors or controllers.
Without further ado, let’s jump right to the example. Let’s implement OCP in a wheeled robot controller, where different types of motion controllers (e.g., PID Controller, MPC Controller) can be added without modifying the base class.
Bad Example That Violates OCP:
Here, the WheeledRobot class has a hardcoded motion control logic. If we want to add a new control method (e.g., MPC-based control), we have to modify the class, violating OCP.
1#include <iostream>
2
3// Robot class with hardcoded control logic (BAD)
4class WheeledRobot {
5public:
6 void move(double target_speed) {
7 // Hardcoded PID control
8 double control_signal = target_speed * 0.8; // Simple proportional control
9 std::cout << "Moving with PID control at speed: " << control_signal << " m/s\n";
10 }
11};
12
13// Usage
14int main() {
15 WheeledRobot robot;
16 robot.move(2.0); // Move at 2 m/s
17 return 0;
18}Why is this bad?
- If we want to add a new control method (e.g., MPC Controller), we must modify WheeledRobot, risking unintended bugs.
- The class is not extendable — all control logic is inside WheeledRobot, violating OCP.
Good Example That Follows OCP:
We separate the motion control logic using polymorphism. Now, we can extend the robot’s behavior by adding new controllers without modifying the WheeledRobot class.
1#include <iostream>
2#include <memory>
3
4// Abstract base class (interface) for motion controllers
5class MotionController {
6public:
7 virtual double computeSpeed(double target_speed) const = 0;
8 virtual ~MotionController() = default;
9};
10
11// Concrete class: PID-based motion controller
12class PIDController : public MotionController {
13public:
14 double computeSpeed(double target_speed) const override {
15 return target_speed * 0.8; // Simple proportional control
16 }
17};
18
19// Concrete class: Model Predictive Control (MPC)
20class MPCController : public MotionController {
21public:
22 double computeSpeed(double target_speed) const override {
23 return target_speed * 0.9; // More advanced control
24 }
25};
26
27// Robot class (depends on MotionController interface, not concrete implementations)
28class WheeledRobot {
29private:
30 std::shared_ptr<MotionController> controller;
31
32public:
33 explicit WheeledRobot(std::shared_ptr<MotionController> ctrl) : controller(std::move(ctrl)) {}
34
35 void move(double target_speed) {
36 double control_signal = controller->computeSpeed(target_speed);
37 std::cout << "Moving with control at speed: " << control_signal << " m/s\n";
38 }
39};
40
41// Usage
42int main() {
43 // Use PID Controller
44 std::shared_ptr<MotionController> pid_ctrl = std::make_shared<PIDController>();
45 WheeledRobot robot1(pid_ctrl);
46 robot1.move(2.0);
47
48 // Use MPC Controller (without modifying WheeledRobot class)
49 std::shared_ptr<MotionController> mpc_ctrl = std::make_shared<MPCController>();
50 WheeledRobot robot2(mpc_ctrl);
51 robot2.move(2.0);
52
53 return 0;
54}Why is this better?
- Follows OCP: We can add new controllers (e.g., LQR Controller, Fuzzy Logic Controller) without modifying WheeledRobot.
- Scalable: The MotionController interface allows extending the system without modifying existing code.
- Loose coupling: WheeledRobot depends on the abstract interface, not a specific control method.
- Easier maintenance: We can test and modify controllers independently.
This design ensures the robot’s motion control is flexible and easily extendable — ideal for real-world robotics software.
Liskov Substitution Principle
The Liskov Substitution Principle (LSP) states that:
“Subtypes must be substitutable for their base types without altering the correctness of the program.”
In simpler terms, if a class inherits from a base class, it should be able to replace the base class without breaking the functionality.
This principle is essential in robotics software to ensure that different robot types (e.g., wheeled robots, legged robots, drones) can be used interchangeably if they share a common base class.
Bad Example (Violates LSP)
Here, we will define a base class WheeledRobot and a subclass called QuadrupedRobot. However as we know that a QuadrupedRobot doesn’t have any wheels, so calling setWheelVelocity() on it would make no sense at all, thus, it’s breaking the LSP.
1#include <iostream>
2
3// Base class for wheeled robots
4class WheeledRobot {
5public:
6 virtual void setWheelVelocity(double velocity) {
7 std::cout << "Setting wheel velocity to: " << velocity << " m/s\n";
8 }
9};
10
11// Quadruped robot mistakenly inherits from WheeledRobot
12class QuadrupedRobot : public WheeledRobot {
13public:
14 void setWheelVelocity(double velocity) override {
15 // Quadruped robots don’t have wheels, so this is incorrect!
16 std::cerr << "Error: Quadruped robots don’t have wheels!\n";
17 }
18};
19
20// Usage
21int main() {
22 WheeledRobot* robot = new QuadrupedRobot();
23 robot->setWheelVelocity(2.0); // Runtime error: Quadruped doesn’t have wheels!
24
25 delete robot;
26 return 0;
27}Why is this bad?
- QuadrupedRobot inherits from WheeledRobot, but it does not behave like a wheeled robot.
- If we substitute WheeledRobot with QuadrupedRobot, the program breaks because QuadrupedRobot does not support wheel velocity control.
- Violates LSP: The subclass should be interchangeable with the base class without breaking the logic.
Good Example (Follows LSP)
To fix this, we should have a more generic base class called MobileRobot, which applies to both wheeled and legged robots. Each subclass implements motion differently.
1#include <iostream>
2#include <memory>
3
4// Generic base class for all mobile robots
5class MobileRobot {
6public:
7 virtual void move(double speed) const = 0; // Abstract method
8 virtual ~MobileRobot() = default;
9};
10
11// Wheeled robot correctly implements movement
12class WheeledRobot : public MobileRobot {
13public:
14 void move(double speed) const override {
15 std::cout << "Wheeled Robot moving at " << speed << " m/s using wheels.\n";
16 }
17};
18
19// Quadruped robot correctly implements movement
20class QuadrupedRobot : public MobileRobot {
21public:
22 void move(double speed) const override {
23 std::cout << "Quadruped Robot moving at " << speed << " m/s using legs.\n";
24 }
25};
26
27// Usage
28int main() {
29 std::shared_ptr<MobileRobot> robot1 = std::make_shared<WheeledRobot>();
30 std::shared_ptr<MobileRobot> robot2 = std::make_shared<QuadrupedRobot>();
31
32 // Both robots can move, following their own logic
33 robot1->move(2.0);
34 robot2->move(1.5);
35
36 return 0;
37}Why is this better?
- Follows LSP: Both WheeledRobot and QuadrupedRobot correctly extend MobileRobot, and they can be used interchangeably.
- No incorrect behavior: QuadrupedRobot does not inherit setWheelVelocity, which wouldn’t make sense for a legged robot.
- Scalable: We can easily add new robot types (e.g., drones, humanoid robots) by extending MobileRobot without breaking existing functionality.
This proper use of LSP ensures that robot subclasses behave correctly and can be safely substituted in a modular robotics system.
Interface Segregation Principle
The Interface Segregation Principle (ISP) states that:
“A class should not be forced to implement interfaces it does not use.”
In robotics software, this means that a robot should only implement the functionalities it needs, rather than being forced to implement unnecessary methods from a large, monolithic interface.
Instead of having one big interface for all robots, we should split it into smaller, more specific interfaces that only contain relevant functionalities.
Bad Example (Violates ISP)
Here, we create a large interface RobotInterface that includes both wheeled and legged robot functionalities. A wheeled robot should not be forced to implement walk()! (somehow, i laugh when I wrote this one, because of that illustration when you ask a fish to climb a tree XD)
1#include <iostream>
2
3// A single, large interface for all robots
4class RobotInterface {
5public:
6 virtual void move(double speed) = 0;
7 virtual void setWheelVelocity(double velocity) = 0; // Only for wheeled robots
8 virtual void walk(double step_length) = 0; // Only for legged robots
9 virtual ~RobotInterface() = default;
10};
11
12// Wheeled robots are forced to implement walk() (incorrect)
13class WheeledRobot : public RobotInterface {
14public:
15 void move(double speed) override {
16 std::cout << "Wheeled Robot moving at " << speed << " m/s\n";
17 }
18
19 void setWheelVelocity(double velocity) override {
20 std::cout << "Setting wheel velocity to " << velocity << " m/s\n";
21 }
22
23 void walk(double step_length) override {
24 // This makes no sense for a wheeled robot!
25 std::cerr << "Error: Wheeled robots cannot walk!\n";
26 }
27};
28
29// Quadruped robots are forced to implement setWheelVelocity() (incorrect)
30class QuadrupedRobot : public RobotInterface {
31public:
32 void move(double speed) override {
33 std::cout << "Quadruped Robot moving at " << speed << " m/s\n";
34 }
35
36 void walk(double step_length) override {
37 std::cout << "Quadruped walking with step length: " << step_length << " meters\n";
38 }
39
40 void setWheelVelocity(double velocity) override {
41 // This makes no sense for a quadruped robot!
42 std::cerr << "Error: Quadruped robots do not have wheels!\n";
43 }
44};
45
46// Usage
47int main() {
48 WheeledRobot wheeledRobot;
49 QuadrupedRobot quadrupedRobot;
50
51 wheeledRobot.walk(0.5); // Invalid function call
52 quadrupedRobot.setWheelVelocity(2.0); // Invalid function call
53
54 return 0;
55}Why is this bad?
- Violates ISP: WheeledRobot is forced to implement walk(), even though it has no legs. It’s just like I force you as a human to breathe underwater. Doesn’t make any sense right?
- Unnecessary methods: QuadrupedRobot must implement setWheelVelocity(), even though it has no wheels.
- Code is harder to maintain: Every new robot type must implement unrelated methods.
Good Example (Follows ISP)
To fix this, we split the large interface into smaller, more specific interfaces, ensuring that robots only implement what they need.
1#include <iostream>
2#include <memory>
3
4// Interface for all mobile robots
5class MobileRobot {
6public:
7 virtual void move(double speed) = 0;
8 virtual ~MobileRobot() = default;
9};
10
11// Interface for wheeled robots
12class WheeledRobotInterface {
13public:
14 virtual void setWheelVelocity(double velocity) = 0;
15 virtual ~WheeledRobotInterface() = default;
16};
17
18// Interface for legged robots
19class LeggedRobotInterface {
20public:
21 virtual void walk(double step_length) = 0;
22 virtual ~LeggedRobotInterface() = default;
23};
24
25// WheeledRobot only implements relevant interfaces
26class WheeledRobot : public MobileRobot, public WheeledRobotInterface {
27public:
28 void move(double speed) override {
29 std::cout << "Wheeled Robot moving at " << speed << " m/s\n";
30 }
31
32 void setWheelVelocity(double velocity) override {
33 std::cout << "Setting wheel velocity to " << velocity << " m/s\n";
34 }
35};
36
37// QuadrupedRobot only implements relevant interfaces
38class QuadrupedRobot : public MobileRobot, public LeggedRobotInterface {
39public:
40 void move(double speed) override {
41 std::cout << "Quadruped Robot moving at " << speed << " m/s\n";
42 }
43
44 void walk(double step_length) override {
45 std::cout << "Quadruped walking with step length: " << step_length << " meters\n";
46 }
47};
48
49// Usage
50int main() {
51 std::shared_ptr<WheeledRobot> wheeledRobot = std::make_shared<WheeledRobot>();
52 std::shared_ptr<QuadrupedRobot> quadrupedRobot = std::make_shared<QuadrupedRobot>();
53
54 wheeledRobot->setWheelVelocity(3.0); // ✅ Works correctly
55 quadrupedRobot->walk(0.7); // ✅ Works correctly
56
57 return 0;
58}Why is this better?
- Follows ISP: Wheeled robots only implement WheeledRobotInterface, and quadruped robots only implement LeggedRobotInterface.
- No unnecessary methods: Each robot class only has the functions it actually needs.
- Modular & Scalable: We can easily add new robot types (e.g., drones) with their own interfaces without affecting existing robots.
By applying Interface Segregation Principle (ISP), we ensure that each robot only implements what is necessary, making our code cleaner, more maintainable, and reusable.
Dependency Inversion Principle
The Dependency Inversion Principle (DIP) states:
“High-level modules should not depend on low-level modules. Both should depend on abstractions (interfaces). Abstractions should not depend on details. Details should depend on abstractions.”
In robotics software, this means that a high-level robot controller should not depend directly on low-level hardware implementations. Instead, both should depend on an abstract interface, making the system more modular and flexible.
Bad Example (Violates DIP)
Here, the RobotController directly depends on the WheeledRobot and LeggedRobot classes, making it tightly coupled. If we want to add a new robot type, we must modify RobotController.
1#include <iostream>
2
3// Low-level class for a wheeled robot
4class WheeledRobot {
5public:
6 void drive(double speed) {
7 std::cout << "Wheeled Robot driving at " << speed << " m/s\n";
8 }
9};
10
11// Low-level class for a legged robot
12class LeggedRobot {
13public:
14 void walk(double step_length) {
15 std::cout << "Legged Robot walking with step length: " << step_length << " meters\n";
16 }
17};
18
19// High-level module (controller) directly depends on low-level implementations
20class RobotController {
21private:
22 WheeledRobot* wheeledRobot;
23 LeggedRobot* leggedRobot;
24
25public:
26 RobotController() {
27 wheeledRobot = new WheeledRobot();
28 leggedRobot = new LeggedRobot();
29 }
30
31 void moveWheeledRobot(double speed) {
32 wheeledRobot->drive(speed);
33 }
34
35 void moveLeggedRobot(double step_length) {
36 leggedRobot->walk(step_length);
37 }
38
39 ~RobotController() {
40 delete wheeledRobot;
41 delete leggedRobot;
42 }
43};
44
45// Usage
46int main() {
47 RobotController controller;
48 controller.moveWheeledRobot(2.0);
49 controller.moveLeggedRobot(0.5);
50 return 0;
51}Why is this bad?
- Violates DIP: The high-level controller depends directly on low-level robot implementations.
- Hard to extend: Adding a new robot type (e.g., a drone) requires modifying RobotController.
- Low flexibility: We cannot swap different robot types easily.
Good Example (Follows DIP)
We introduce an abstract interface (RobotInterface), so the controller does not depend on specific robot implementations. Instead, both the high-level controller and low-level robots depend on the interface.
1#include <iostream>
2#include <memory>
3
4// Abstract interface for all robots
5class RobotInterface {
6public:
7 virtual void move(double speed) = 0;
8 virtual ~RobotInterface() = default;
9};
10
11// Low-level class for a wheeled robot
12class WheeledRobot : public RobotInterface {
13public:
14 void move(double speed) override {
15 std::cout << "Wheeled Robot driving at " << speed << " m/s\n";
16 }
17};
18
19// Low-level class for a legged robot
20class LeggedRobot : public RobotInterface {
21public:
22 void move(double speed) override {
23 std::cout << "Legged Robot walking at " << speed << " m/s\n";
24 }
25};
26
27// High-level module (controller) depends on abstraction, not concrete classes
28class RobotController {
29private:
30 std::shared_ptr<RobotInterface> robot;
31
32public:
33 RobotController(std::shared_ptr<RobotInterface> r) : robot(r) {}
34
35 void moveRobot(double speed) {
36 robot->move(speed);
37 }
38};
39
40// Usage
41int main() {
42 std::shared_ptr<RobotInterface> wheeledRobot = std::make_shared<WheeledRobot>();
43 std::shared_ptr<RobotInterface> leggedRobot = std::make_shared<LeggedRobot>();
44
45 RobotController controller1(wheeledRobot);
46 controller1.moveRobot(2.0); // Works with wheeled robot
47
48 RobotController controller2(leggedRobot);
49 controller2.moveRobot(1.0); // Works with legged robot
50
51 return 0;
52}Why is this better?
- Follows DIP: The controller depends on an abstraction (RobotInterface) instead of specific robot classes.
- Easily extensible: We can add a new robot type (e.g., a drone) without modifying RobotController.
- Flexible & Modular: We can swap robot implementations dynamically at runtime.
By applying the Dependency Inversion Principle (DIP), our robot software becomes more scalable, maintainable, and adaptable to future changes.
Closing Statement and Conclusion
The SOLID principles provide a strong foundation for developing scalable, maintainable, and robust robotics software. By applying these principles, we ensure that our system remains modular, flexible, and adaptable to future changes, reducing technical debt and improving overall software quality.
Each principle plays a crucial role in robotics software development:
- Single Responsibility Principle (SRP) ensures that each component has a clear and well-defined function.
- Open/Closed Principle (OCP) allows for system expansion without modifying existing code.
- Liskov Substitution Principle (LSP) guarantees that derived classes can replace base classes without breaking functionality.
- Interface Segregation Principle (ISP) prevents bloated interfaces, making code easier to maintain and extend.
- Dependency Inversion Principle (DIP) decouples high-level logic from low-level implementations, enabling better reusability and flexibility.
By following SOLID principles, we create modular robotics architectures that are easier to test, debug, and extend. This is especially important in real-world robotics applications, where system requirements continuously evolve, and integration with new hardware or algorithms is a common challenge.
Final Thought
In robotics, where hardware and software must work seamlessly together, applying SOLID principles helps us design software that is not only functional but also adaptable and scalable. Whether you’re building autonomous navigation systems, robot controllers, or simulation environments, embracing these best practices will result in efficient, maintainable, and future-proof robotic software.
References
- https://www.digitalocean.com/community/conceptual-articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design#dependency-inversion-principle
- https://corecppil.github.io/Meetups/2020-05-26_CoreCpp_Worldwide!/The_SOLID_Principles.pdf
- https://en.cppreference.com/w/cpp/20
Originally published on Medium: https://medium.com/@danendraclever24/mastering-solid-principles-in-modern-c-20-with-robotics-examples-6fd07c68dbfc