Single Responsibility Priciple - Dieptranivsr/DroneIVSR GitHub Wiki
Single Responsibility Priciple (SRP)
the class should have only reason to change. In other words, it should have only one responsibility.
this principle create more modules, maintainable and understandable code.
Here is an example - Managing Journal Entries storing in a File/Database.
/** * Bad Example **/// The Journal class has two responsibilyties: managing journal entries and saving them to a file. If the storage machanism changes (e.g. saving to a database), you'd have to// modify the Journal class. This violates SRP.
#include<iostream>
#include<fstream>
#include<string>
#include<vector>classJournal {
public:voidaddEntry(const std::string& entry) { entries_.push_back(entry); }
voidsaveToFile(const std::string& filename) {
std::ofstream ofs(filename);
for (constauto& e : entries_) {
ofs << e << std << endl;
}
}
private:
std::vector<std::string> entries_;
};
intmain() {
Journal journal;
journal.addEntry("Dear Diary, today I learned about SRP");
journal.addEntry("It's a very important principle.");
journal.saveToFile("my_journal.txt");
return0;
}
/** * Good Example **//** * We've separated the responsibilities: * - Journal class manages journal entries. * - PersistanceManager class handles saving to a file. * Now if the persistance machanism changes, you only need to modify PersistanceManager, leaving Journal untouched **/
#include<iostream>
#include<fstream>
#include<string>
#include<vector>classJournal {
public:voidaddEntry(const std::string& entry) {entries_.push_back(entry); }
std::vector<std::strong> getEntries() const { return entries_; }
private:
std::vector<std::string> entries_;
};
classPersistanceManager {
public:staticvoidsaveToFile(const Journal& j, const std::string& filename) {
std::ofstream ofs(filestream);
for (constauto& e : j.getEntries()) {
ofs << e << std::endl;
}
}
};
intmain() {
Journal journal;
journal.addEntry("Dear Diary, today I leared about SRP.");
journal.addEntry("It's a very important principle.");
PersistanceManager::saveToFile(journal, "my_journal.txt");
return0;
}