Open Closed Principle | SOLID as a Rock
Tags: cpp, programming, tutorial, codenewbie
Published: 2020-05-11 12:20:07

<!-- wp:paragraph -->
<p>This is the second part of a five-part series about SOLID as Rock design principle. The SOLID design principles, when combined together, make it easy for a programmer to craft software that is easy to maintain, reuse &amp; extend. <strong>O</strong>pen-<strong>C</strong>losed <strong>P</strong>rinciple(OCP) is the second principle in this series which I will discuss here with minimalistic example in <a href="http://www.vishalchovatiya.com/21-new-features-of-modern-cpp-to-use-in-your-project/" target="_blank" rel="noreferrer noopener" aria-label="Modern C++ (opens in a new tab)"><span style="color:#0007a3" class="color">Modern C++</span></a> along with its benefits &amp; generic guideline.</p>
<!-- /wp:paragraph -->

> /!\\\: This article has been originally published on my [blog](http://www.vishalchovatiya.com/open-closed-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 haven't gone through my previous articles on 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/)

The code snippets you see throughout this series of articles are simplified not sophisticated. So you often see me not using keywords like `override`, `final`, `public`(while inheritance) just to make code compact & consumable(most of the time) in single standard screen size. I also prefer `struct` instead of `class` just to save line by not writing "`public:`" sometimes and also miss [virtual destructor](http://www.vishalchovatiya.com/part-3-all-about-virtual-keyword-in-c-how-virtual-destructor-works/), constructor, [copy constructor](http://www.vishalchovatiya.com/all-about-copy-constructor-in-cpp-with-example/), prefix `std::`, deleting dynamic memory, intentionally. I also consider myself a pragmatic person who wants to convey an idea in the simplest way possible rather than the standard way or using Jargons.

***Note:***

-   If you stumbled here directly, then I would suggest you go through [What is design pattern?](http://www.vishalchovatiya.com/what-is-design-pattern/) first, even if it is trivial. I believe it will encourage you to explore more on this topic.
-   All of this code you encounter in this series of articles are compiled using C++20(though I have used [Modern C++](http://www.vishalchovatiya.com/21-new-features-of-modern-cpp-to-use-in-your-project/) features up to C++17 in most cases). So if you don't have access to the latest compiler you can use <https://wandbox.org/> which has preinstalled boost library as well.

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

> classes should be open for extension, closed for modification

<!-- wp:list -->
<ul><li>This literally means you should be able to extend a classes behaviour, without modifying it. This might seems weird to you &amp; may raise a question that how can you change the behaviour of a class without modifying it? </li><li>But there are many answers to this in <a rel="noreferrer noopener" aria-label="object-oriented design (opens in a new tab)" href="http://www.vishalchovatiya.com/memory-layout-of-cpp-object/" target="_blank"><span style="color:#0002a3" class="color">object-oriented design</span></a> like <a rel="noreferrer noopener" aria-label="dynamic polymorphism (opens in a new tab)" href="http://www.vishalchovatiya.com/part-1-all-about-virtual-keyword-in-cpp-how-virtual-function-works-internally/" target="_blank"><span style="color:#002ea3" class="color">dynamic polymorphism</span></a>, <a rel="noreferrer noopener" aria-label="static polymorphism (opens in a new tab)" href="http://www.vishalchovatiya.com/7-advanced-cpp-concepts-idiom-examples-you-should-know/#CRTP" target="_blank"><span style="color:#001fa3" class="color">static polymorphism</span></a>, template, etc.  </li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Violating the Open Closed Principle</h2>
<!-- /wp:heading -->

```c++
enum class COLOR { RED, GREEN, BLUE };
enum class SIZE { SMALL, MEDIUM, LARGE };

struct Product {
    string  m_name;
    COLOR   m_color;
    SIZE    m_size;
};

using Items = vector<Product*>;

#define ALL(C)  begin(C), end(C)

struct ProductFilter {
    static Items by_color(Items items, const COLOR e_color) {
        Items result;
        for (auto &i : items)
            if (i->m_color == e_color)
                result.push_back(i);
        return result;
    }
    static Items by_size(Items items, const SIZE e_size) {
        Items result;
        for (auto &i : items)
            if (i->m_size == e_size)
                result.push_back(i);
        return result;
    }
    static Items by_size_and_color(Items items, const SIZE e_size, const COLOR e_color) {
        Items result;
        for (auto &i : items)
            if (i->m_size == e_size && i->m_color == e_color)
                result.push_back(i);
        return result;
    }
};

int main() {
    const Items all{
        new Product{"Apple", COLOR::GREEN, SIZE::SMALL},
        new Product{"Tree", COLOR::GREEN, SIZE::LARGE},
        new Product{"House", COLOR::BLUE, SIZE::LARGE},
    };
    for (auto &p : ProductFilter::by_color(all, COLOR::GREEN))
        cout << p->m_name << " is green\n";
    for (auto &p : ProductFilter::by_size_and_color(all, SIZE::LARGE, COLOR::GREEN))
        cout << p->m_name << " is green & large\n";
    return EXIT_SUCCESS;
}

/*
Apple is green
Tree is green
Tree is green & large
*/
```

<!-- wp:list -->
<ul><li>So we have a bunch of products &amp; we filtered it by some of its attributes. There is nothing wrong with the above code as far as the requirement is fixed(which will never be the case in software engineering). </li><li>But just imagine the situations: You already shipped the code to the client. Later on, requirement changes &amp; some new filters are required. In this case, you again need to modify the class &amp; add new filter methods.</li><li>This is a problematic approach because we have 2 attributes(i.e. color &amp; size) &amp; need to implement 3 function(i.e. color, size &amp; its combination), one more attributes &amp; need to implement 8 functions. You see where this is going.</li><li>You need to go again &amp; again in the existing implemented code &amp; have to modify it which may break other parts of code as well. This is not a scalable solution. </li><li>The open-closed principle states that your system should be open to extension but should be closed for modification. Unfortunately what we are doing here is modifying the existing code which is a violation of OCP.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Open Closed Principle Example</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>There is more than one way to achieve OCP. Here I am demonstrating the popular one i.e. interface design or abstraction level. So here is our scalable solution:</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Adding the level of abstraction for extensibility</h3>
<!-- /wp:heading -->

```c++
template <typename T>
struct Specification {
    virtual ~Specification() = default;
    virtual bool is_satisfied(T *item) const = 0;
};

struct ColorSpecification : Specification<Product> {
    COLOR e_color;
    ColorSpecification(COLOR e_color) : e_color(e_color) {}
    bool is_satisfied(Product *item) const { return item->m_color == e_color; }
};

struct SizeSpecification : Specification<Product> {
    SIZE e_size;
    SizeSpecification(SIZE e_size) : e_size(e_size) {}
    bool is_satisfied(Product *item) const { return item->m_size == e_size; }
};

template <typename T>
struct Filter {
    virtual vector<T *> filter(vector<T *> items, const Specification<T> &spec) = 0;
};

struct BetterFilter : Filter<Product> {
    vector<Product *> filter(vector<Product *> items, const Specification<Product> &spec) {
        vector<Product *> result;
        for (auto &p : items)
            if (spec.is_satisfied(p))
                result.push_back(p);
        return result;
    }
};

// ------------------------------------------------------------------------------------------------
BetterFilter bf;
for (auto &x : bf.filter(all, ColorSpecification(COLOR::GREEN)))
    cout << x->m_name << " is green\n";
```

<!-- wp:list -->
<ul><li>As you can see we do not have to modify <code>filter</code> method of <code>BetterFilter</code>. It can work with all kind of <code>specification</code> now. </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>For two or more combined specifications</h3>
<!-- /wp:heading -->

```c++
template <typename T>
struct AndSpecification : Specification<T> {
    const Specification<T> &first;
    const Specification<T> &second;

    AndSpecification(const Specification<T> &first, const Specification<T> &second)
    : first(first), second(second) {}

    bool is_satisfied(T *item) const { 
        return first.is_satisfied(item) && second.is_satisfied(item); 
    }
};

template <typename T>
AndSpecification<T> operator&&(const Specification<T> &first, const Specification<T> &second) {
    return {first, second};
}

// -----------------------------------------------------------------------------------------------------

auto green_things = ColorSpecification{COLOR::GREEN};
auto large_things = SizeSpecification{SIZE::LARGE};

BetterFilter bf;
for (auto &x : bf.filter(all, green_things &&large_things))
    cout << x->m_name << " is green and large\n";

// warning: the following will compile but will NOT work
// auto spec2 = SizeSpecification{SIZE::LARGE} &&
//              ColorSpecification{COLOR::BLUE};
```

<!-- wp:list -->
<ul><li><code>SizeSpecification{SIZE::LARGE} &amp;&amp; ColorSpecification{COLOR::BLUE}</code> will not work. Experienced C++ eyes can easily recognize the reason. Though temporary object creation is a hint here.  If you do so, you may get the error of <a href="http://www.vishalchovatiya.com/part-1-all-about-virtual-keyword-in-cpp-how-virtual-function-works-internally/" target="_blank" rel="noreferrer noopener" aria-label="pure virtual function (opens in a new tab)"><span style="color:#0015a3" class="color">pure virtual function</span></a> as follows:</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pure virtual method called
terminate called without an active exception
The terminal process terminated with exit code: 3</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>For more than two specifications, you can use a variadic template.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Benefits of Open Closed Principle</h2>
<!-- /wp:heading -->

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

<!-- wp:paragraph {"align":"center","backgroundColor":"very-light-gray"} -->
<p class="has-background has-text-align-center has-very-light-gray-background-color">"When a single change to a program results in a cascade of changes to dependent modules, that program exhibits the undesirable attributes that we have come to associate with 'bad' design. The program becomes fragile, rigid, unpredictable and unreusable. The open-closed principle attacks this in a very straightforward way. It says that you should design modules that never change. When requirements change, you extend the behaviour of such modules by adding new code, not by changing old code that already works."<br>  — <a href="https://en.wikipedia.org/wiki/Robert_C._Martin" target="_blank" rel="noreferrer noopener" aria-label="Robert Martin (opens in a new tab)"><span style="color:#000ba3" class="color">Robert Martin</span></a> </p>
<!-- /wp:paragraph -->

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

<!-- wp:list -->
<ul><li>The main benefit of this approach is that an interface introduces an additional level of abstraction which enables loose coupling. The implementations of an interface are independent of each other and don’t need to share any code. </li><li>Thus, you can easily cope-up with client's keep changing requirements. Very useful in agile methodologies.</li></ul>
<!-- /wp:list -->

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

<!-- wp:list -->
<ul><li>The open-closed principle also applies to plugin and middleware architecture. In that case, your base software entity is your application core functionality.</li><li>In the case of plugins, you have a base or core module that can be plugged with new features &amp; functionality through a common gateway interface. A good example of this is web browser extensions. </li><li>Binary compatibility will also be in-tact in subsequent releases.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Yardstick to Craft Open Closed Principle Friendly Software</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>In the SRP, you make a judgement about decomposition and where to draw encapsulation boundaries in your code. In the OCP, you make a judgement about what in your module you will make abstract and leave to your module’s consumers to make concrete, and what concrete functionality to provide yourself. </li><li>There are many design patterns that help us to extend code without changing it. For instance, the <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/decorator-design-pattern-in-modern-cpp/" target="_blank"><span style="color:#170cec" class="color">Decorator pattern</span></a> helps us to follow Open Close principle. Also, the <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/factory-design-pattern-in-modern-cpp/" target="_blank"><span style="color:#170cec" class="color">Factory Method</span></a>, <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/strategy-design-pattern-in-modern-cpp/" target="_blank"><span style="color:#170cec" class="color">Strategy pattern</span></a> or the <a href="http://www.vishalchovatiya.com/observer-design-pattern-in-modern-cpp/" target="_blank" rel="noreferrer noopener"><span style="color:#170cec" class="color">Observer pattern</span></a> might be used to design an application easy to change with minimum changes in the existing code. </li></ul>
<!-- /wp:list -->

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

<!-- wp:paragraph -->
<p>Keep in mind that classes can never be&nbsp;completely&nbsp;closed. There will always be unforeseen changes which require a class to be modified. However, if changes can be foreseen, such as seen above i.e. <code>filters</code>, then you have a perfect opportunity to apply the OCP to be future-ready when those change requests come rolling in. </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/)🖱️