Single Responsibility Principle | SOLID as a Rock
Tags: cpp, design, pattern, tutorial
Published: 2020-05-04 04:32:11

<!-- wp:paragraph -->
<p>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 &amp; extendable. In this article, we will see an example of the <strong>S</strong>ingle <strong>R</strong>esponsibility <strong>P</strong>rinciple in C++ along with its benefits &amp; generic guideline.</p>
<!-- /wp:paragraph -->


> /!\\\: This article has been originally published on my [blog](http://www.vishalchovatiya.com/single-responsibility-principle-in-cpp-solid-as-a-rock/). If you are interested in receiving my latest articles, [please sign up to my newsletter](http://eepurl.com/gDNybv).

<!-- wp:paragraph -->
<p>By the way, If you wants to directly jumps to other design principles, then below is the quick links: </p>
<!-- /wp:paragraph -->

1.  [**S**RP -- Single Responsibility Principle](http://www.vishalchovatiya.com/single-responsibility-principle-in-cpp-solid-as-a-rock/)
2.  [**O**CP -- Open/Closed Principle](http://www.vishalchovatiya.com/open-closed-principle-in-cpp-solid-as-a-rock/)
3.  [**L**SP -- Liskov Substitution Principle](http://www.vishalchovatiya.com/liskovs-substitution-principle-in-cpp-solid-as-a-rock/)
4.  [**I**SP -- Interface Segregation Principle](http://www.vishalchovatiya.com/interface-segregation-principle-in-cpp-solid-as-a-rock/)
5.  [**D**IP -- Dependency Inversion Principle](http://www.vishalchovatiya.com/dependency-inversion-principle-in-cpp-solid-as-a-rock/)

<!-- wp:heading -->
<h2>Intent</h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"center","backgroundColor":"very-light-gray"} -->
<p class="has-background has-text-align-center has-very-light-gray-background-color"> <strong><em>A class should have only one reason to change </em></strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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." </p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Motivation: Violating the Single Responsibility Principle</h2>
<!-- /wp:heading -->

```c++
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;
}
```

<!-- wp:list -->
<ul><li>Above C++ example seems fine as long as you have a single domain object i.e. <code>Journal</code>. but this is not usually the case in a real-world application. </li><li>As we start adding domain objects like <code>Book</code>, <code>File</code>, etc. you have to implement save method for everyone separately which is not the actual problem.</li><li>The real problem arises when you have to change or maintain <code>save</code> functionality. For instance, some other day you will no longer save data on files &amp; adopted database. In this case, you have to go through every domain <a rel="noreferrer noopener" aria-label="object implementation (opens in a new tab)" href="http://www.vishalchovatiya.com/inside-the-cpp-object-model/" target="_blank"><span style="color:#0015a3" class="color">object implementation</span></a> &amp; need to change code all over which is not good. </li><li>Here, we have violated the Single Responsibility Principle by providing <code>Journal</code> class two reason to change i.e. <ul><li>Things related to <code>Journal</code> </li><li>Saving the <code>Journal</code></li></ul></li><li>Moreover, code will also become repetitive, bloated &amp; hard to maintain.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Solution: Single Responsibility Principle Example in C++</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>As a solution what we do is a <strong><em><a rel="noreferrer noopener" aria-label="separation of concerns (opens in a new tab)" href="https://en.wikipedia.org/wiki/Separation_of_concerns" target="_blank"><span style="color:#1200a3" class="color">separation of concerns</span></a></em></strong>.</li></ul>
<!-- /wp:list -->

```c++
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");
```

<!-- wp:list -->
<ul><li><code>Journal</code> should only take care of entries &amp; things related to the journal. </li><li>And there should be one separate central location or entity which does the work of saving. In our case, its  <code>SavingManager</code>.</li><li>As your <code>SavingManager</code> grows, you have all the saving related code will be at one place. You can also templatize it to accept more domain <a href="http://www.vishalchovatiya.com/memory-layout-of-cpp-object/" target="_blank" rel="noreferrer noopener" aria-label="object (opens in a new tab)"><span style="color:#0300a3" class="color">object</span></a>s.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Benefits of Single Responsibility Principle </h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>=&gt; Expressiveness</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>When the class only does one thing, its interface usually has a small number of methods which is more expressive. Hence, It also has a small number of data members.  </li><li>This improves your development speed &amp; makes your life as a software developer a lot easier. </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>=&gt; Maintainability</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>We all know that requirements change over time &amp; so does the design/architecture. The more responsibilities your class has, the more often you need to change it.  If your class implements multiple responsibilities, they are no longer independent of each other. </li><li>Isolated changes reduce the breaking of other unrelated areas of the software. </li><li>As programming errors are inversely proportional to complexity, being easier to understand makes the code less prone to bugs &amp; easier to maintain.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>=&gt; Reusability</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>If a class has multiple responsibilities and only one of those needs in another area of the software, then the other unnecessary responsibilities hinder reusability. </li><li>Having a single responsibility means the class should be reusable without or less modification.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Yardstick to Craft SRP Friendly Software in C++</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>SRP is a double-edged sword. Be too specific &amp; you will end up having hundreds of ridiculously interconnected classes, that could easily be one. </li><li>You should not use SOLID principles when you feel you are over-engineering. If you boil down the Single Responsibility Principle, the generic idea would be like this:</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph {"backgroundColor":"very-light-gray"} -->
<p class="has-background has-very-light-gray-background-color"><strong><em>The SRP is about limiting the impact of&nbsp;change. So, gather together the things that change for the same reasons. Separate those things that change for different reasons.</em></strong></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Adding more to this, If your class constructor has more than 5-6 parameters then it means either you are not followed SRP or you are not aware of builder design pattern.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Conclusion</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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.</p>
<!-- /wp:paragraph -->

[Have Any Suggestions, Query or Wants to Say `Hi`? Take the Pressure Off, You Are Just a Click Away.](http://www.vishalchovatiya.com/contact-2/)🖱️