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>

class Journal {
 public:
    void addEntry(const std::string& entry) { entries_.push_back(entry); }

    void saveToFile(const std::string& filename) {
        std::ofstream ofs(filename);
        for (const auto& e : entries_) {
            ofs << e << std << endl;
        }
    }

 private:
    std::vector<std::string> entries_;
};

int main() {
    Journal journal;
    journal.addEntry("Dear Diary, today I learned about SRP");
    journal.addEntry("It's  a very important principle.");
    journal.saveToFile("my_journal.txt");
    return 0;
}
/**
  * 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>

class Journal {
 public:
    void addEntry(const std::string& entry) {entries_.push_back(entry); }
    std::vector<std::strong> getEntries() const { return entries_; }

 private:
    std::vector<std::string> entries_;
};

class PersistanceManager {
 public:
    static void saveToFile(const Journal& j, const std::string& filename) {
        std::ofstream ofs(filestream);
        for (const auto& e : j.getEntries()) {
            ofs << e << std::endl;
        }
    }
};

int main() {
    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");
    return 0;
}

image

⚠️ **GitHub.com Fallback** ⚠️