I've been reading a bit through Clean Code and I came across the Single Responsibility Principle. The principle states that every class should have only one responsibility.
An example taken from chatGPT gives me this:
#include <iostream>
#include <vector>
#include <string>
class Product {
public:
Product(std::string n, double p) : name(n), price(p) {}
std::string getName() {
return name;
}
double getPrice() {
return price;
}
private:
std::string name;
double price;
};
class Inventory {
public:
void addProduct(Product product) {
products.push_back(product);
}
void listProducts() {
for (const auto& product : products) {
std::cout << "Product: " << product.getName() << ", Price: $" << product.getPrice() << std::endl;
}
}
private:
std::vector<Product> products;
};
In this example the class Product
holds all the variables related to a Product
it doesn't allow to do any operations on them. Inventory
instead is a class whose responsibility is to hold a list of products.
Many examples I've seen around are very similar to the one above (including the one provided in Clean Code).
What I don't understand however is how would the principle apply to a class like the following
#include <iostream>
#include <string>
class Vector2D {
public:
Vector2D(double x, double y):mX(x),mY(y) {}
Vector2D operator+(const Vector2D& rhs) const {
return Vector2D(getX() + rhs.getX(), getY() + rhs.getY());
}
double operator*(const Vector2D& rhs) const {
return getX()*rhs.getX() + getY()*rhs.getY();
}
double getX() const {
return mX;
}
double getY() const {
return mY;
}
void setX(double x) {
mX = x;
}
void setY(double y) {
mY = y;
}
private:
double mX;
double mY;
};
In this class I see two responsibilities. The first is holding the data of the 2D vector while the second is to perform operations with other 2D vectors.
This sounds natural to me, but I think if I had to follow the SRP I should probably separate the two responsibilities with either a separate class modelling the operators on 2D vectors or maybe having a namespace with only just operators.
Is this interpretation of mine of the SRP for this example correct? Any examples from literature or just some random code would be useful to clarify the idea.