This article is the first part of a five-part series about SOLID as
Rock design principle series. The SOLID design principles focus on
developing software that is easy to maintainable, reusable &
extendable. In this article, we will see an example of the Single Responsibility Principle in C++ along with its benefits & generic guideline.
/!\: Originally published @ www.vishalchovatiya.com.
By the way, If you haven't gone through my previous articles on design principles, then below is the quick links:
A class should have only one reason to change
In other words, SRP states that classes should be cohesive to the
point that it has a single responsibility, where responsibility defines
as "a reason for the change."
class Journal {
string m_title;
vector<string> m_entries;
public:
explicit Journal(const string &title) : m_title{title} {}
void add_entries(const string &entry) {
static uint32_t count = 1;
m_entries.push_back(to_string(count++) + ": " + entry);
}
auto get_entries() const { return m_entries; }
void save(const string &filename) {
ofstream ofs(filename);
for (auto &s : m_entries) ofs << s << endl;
}
};
int main() {
Journal journal{"Dear XYZ"};
journal.add_entries("I ate a bug");
journal.add_entries("I cried today");
journal.save("diary.txt");
return EXIT_SUCCESS;
}
class Journal {
string m_title;
vector<string> m_entries;
public:
explicit Journal(const string &title) : m_title{title} {}
void add_entries(const string &entry) {
static uint32_t count = 1;
m_entries.push_back(to_string(count++) + ": " + entry);
}
auto get_entries() const { return m_entries; }
//void save(const string &filename)
//{
// ofstream ofs(filename);
// for (auto &s : m_entries) ofs << s << endl;
//}
};
struct SavingManager {
static void save(const Journal &j, const string &filename) {
ofstream ofs(filename);
for (auto &s : j.get_entries())
ofs << s << endl;
}
};
SavingManager::save(journal, "diary.txt");
=> Expressiveness
=> Maintainability
=> Reusability
The SRP is about limiting the impact of change. So, gather together the things that change for the same reasons. Separate those things that change for different reasons.
The SRP is a widely quoted justification for refactoring. This is
often done without a full understanding of the point of the SRP and its
context, leading to fragmentation of codebases with a range of negative
consequences. Instead of being a one-way street to minimally sized
classes, the SRP is actually proposing a balance point between
aggregation and division.
Have Any Suggestions, Query or Wants to Say Hi? Take the Pressure Off, You Are Just a Click Away.🖱️