Builder Design Pattern in Modern C++
Tags: cpp, codequality, tutorial, design
Published: 2020-07-06 03:22:57

<!-- wp:paragraph -->
<p>In software engineering, Creational Design Patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic or ordinary form of object creation could result in design problems or added complexity to the design. Builder Design Pattern in C++ solves this specific problem by <strong><em>separating the construction of a complex object from its representation</em></strong>.</p>
<!-- /wp:paragraph -->



> /!\\\: This article has been originally published on my [blog](http://www.vishalchovatiya.com/builder-design-pattern-in-modern-cpp/). 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 check out my other articles on Creational Design Patterns, then here is the list:</p>
<!-- /wp:paragraph -->

1.  **[Factory](http://www.vishalchovatiya.com/factory-design-pattern-in-modern-cpp/)**
2.  **[Builder](http://www.vishalchovatiya.com/builder-design-pattern-in-modern-cpp/)**
3.  **[Prototype](http://www.vishalchovatiya.com/prototype-design-pattern-in-modern-cpp/)**
4.  **[Singleton](http://www.vishalchovatiya.com/singleton-design-pattern-in-modern-cpp/)**

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 -->

> ***To create/instantiate complex & complicated object piecewise & succinctly by providing an API in a separate entity.***

<!-- wp:list -->
<ul><li>Builder Design Pattern is used when we want to construct a complex object. However, we do not want to have a complex constructor member or one that would need many arguments. </li><li>The Builder Design Pattern constructs a complex object step by step & the final step will return the object. The process of constructing an object should be generic so that it can be used to create different representations of the same object with the help of a variety of methods.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Life Without Builders</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Suppose you have to create the HTML generator using C++ then very naïve way to do it is :</li></ul>
<!-- /wp:list -->

```C++
// <p>hello</p>
auto text = "hello";
string output;
output += "<p>";
output += text;
output += "</p>";
printf("<p>%s</p>", text);

// <ul><li>hello</li><li>world</li></ul>
string words[] = {"hello", "world"};
ostringstream oss;
oss < "<ul>";
for (auto w : words)
    oss < "  <li>" < w < "</li>";
oss < "</ul>";
printf(oss.str().c_str());
```

<!-- wp:list -->
<ul><li>A sophisticated dev will create a class with a bunch of constructor argument & method to add a child node. This is a good approach though but it may complicate the object representation.</li><li>In general, some objects are simple & can be created in a single constructor call while other objects require a lot of ceremonies to create.</li><li>Having an object with 10 constructor arguments is not productive. Instead, we should opt for piecewise construction.</li><li>Builder provides an API for constructing an object step-by-step without revealing actual object representation.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Builder Design Pattern Example in Modern C++</h2>
<!-- /wp:heading -->

```C++
class HtmlBuilder;

class HtmlElement {
    string                      m_name;
    string                      m_text;
    vector<HtmlElement>         m_childs;
    constexpr static size_t     m_indent_size = 4;

    HtmlElement() = default;
    HtmlElement(const string &name, const string &text) : m_name(name), m_text(text) {}
    friend class HtmlBuilder;

public:
    string str(int32_t indent = 0) {
        ostringstream oss;
        oss << string(m_indent_size * indent, ' ') << "<" << m_name << ">" << endl;

        if (m_text.size()) oss << string(m_indent_size * (indent + 1), ' ') << m_text << endl;

        for (auto &element : m_childs)
            oss << element.str(indent + 1);

        oss << string(m_indent_size * indent, ' ') << "</" << m_name << ">" << endl;
        return oss.str();
    }
    static unique_ptr<HtmlBuilder> build(string root_name) { return make_unique<HtmlBuilder>(root_name); }
};

class HtmlBuilder {
    HtmlElement     m_root;

public:
    HtmlBuilder(string root_name) { m_root.m_name = root_name; }
    HtmlBuilder *add_child(string child_name, string child_text) {
        m_root.m_childs.emplace_back(HtmlElement{child_name, child_text});
        return this;
    }
    string str() { return m_root.str(); }
    operator HtmlElement() { return m_root; }
};

int main() {
    auto builder = HtmlElement::build("ul");
    builder->add_child("li", "hello")->add_child("li", "world");

    cout << builder->str() << endl;
    return EXIT_SUCCESS;
}
/*
<ul>
    <li>
        hello
    </li>
    <li>
        world
    </li>
</ul>
*/
```

<!-- wp:list -->
<ul><li>We are forcing users here to use builder by making data members of <code>HtmlElements</code> private.</li><li>As you can see, we have declared the <code>HtmlBuilder</code> & <code>HtmlElement</code> in the same file & to do so, we need forward declaration i.e. <code>class HtmlBuilder;</code> as it is an <a href="https://docs.microsoft.com/en-us/cpp/c-language/incomplete-types" target="_blank" rel="noreferrer noopener"><span style="color:#192bcd" class="color">incomplete type</span></a>. And we can not create the object of incomplete type before compiler parses its actual declaration. The reason is simple, the compiler needs the size of an object to allocate memory for it. Hence pointer is only way around so we have taken <code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="http://www.vishalchovatiya.com/understanding-unique-ptr-with-example-in-cpp11/" target="_blank"><span style="color:#0007a3" class="color">unique_ptr</span></a><HtmlBuilder&gt;</code>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Sophisticated&nbsp;&amp; Fluent Builder Design Pattern Example</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Following is the more sophisticated example of the Builder Design Pattern organized in four different files(i.e. <code>Person.h</code>, <code>Person.cpp</code>, <code>PersonBuilder.h</code> <code>PersonBuilder.cpp</code>). </li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p><strong><code>Person.h</code></strong></p>
<!-- /wp:paragraph -->

```C++
#pragma once
#include <iostream>
using namespace std;

class PersonBuilder;

class Person
{
    std::string m_name, m_street_address, m_post_code, m_city;  // Personal Detail
    std::string m_company_name, m_position, m_annual_income;    // Employment Detail

    Person(std::string name) : m_name(name) {}

public:
    friend class PersonBuilder;
    friend ostream& operator<<(ostream&  os, const Person& obj);
    static PersonBuilder create(std::string name);
};
```

<!-- wp:paragraph -->
<p><code><strong>Person.cpp</strong></code></p>
<!-- /wp:paragraph -->

```C++
#include <iostream>
#include "Person.h"
#include "PersonBuilder.h"

PersonBuilder Person::create(string name) { return PersonBuilder{name}; }

ostream& operator<<(ostream& os, const Person& obj)
{
    return os << obj.m_name
              << std::endl
              << "lives : " << std::endl
              << "at " << obj.m_street_address
              << " with postcode " << obj.m_post_code
              << " in " << obj.m_city
              << std::endl
              << "works : " << std::endl
              << "with " << obj.m_company_name
              << " as a " << obj.m_position
              << " earning " << obj.m_annual_income;
}
```

<!-- wp:list -->
<ul><li>As you can see from the above example <code>Person</code> may have many details like Personal & Professional. And so does the count of data members. </li><li>In our case, there are 7 data members. Having a single class for all the actions needed to create a Person through constructor might make our class bloated & lose its original purpose. Moreover, the library user needs to take care of all those constructor parameters sequence.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p><strong><code>PersonBuilder.h</code></strong></p>
<!-- /wp:paragraph -->

```C++
#pragma once
#include "Person.h"

class PersonBuilder
{
    Person person;

public:
    PersonBuilder(string name) : person(name) {}

    operator Person() const { return move(person); }

    PersonBuilder&  lives();
    PersonBuilder&  at(std::string street_address);
    PersonBuilder&  with_postcode(std::string post_code);
    PersonBuilder&  in(std::string city);
    PersonBuilder&  works();
    PersonBuilder&  with(string company_name);
    PersonBuilder&  as_a(string position);
    PersonBuilder&  earning(string annual_income);
};
```

<!-- wp:paragraph -->
<p><strong><code>PersonBuilder.cpp</code></strong></p>
<!-- /wp:paragraph -->

```C++
#include "PersonBuilder.h"

PersonBuilder&  PersonBuilder::lives() { return *this; }

PersonBuilder&  PersonBuilder::works() { return *this; }

PersonBuilder&  PersonBuilder::with(string company_name) {
    person.m_company_name = company_name; 
    return *this;
}

PersonBuilder&  PersonBuilder::as_a(string position) {
    person.m_position = position; 
    return *this;
}

PersonBuilder&  PersonBuilder::earning(string annual_income) {
    person.m_annual_income = annual_income; 
    return *this;
}

PersonBuilder&  PersonBuilder::at(std::string street_address) {
    person.m_street_address = street_address; 
    return *this;
}

PersonBuilder&  PersonBuilder::with_postcode(std::string post_code) {
    person.m_post_code = post_code; 
    return *this;
}

PersonBuilder&  PersonBuilder::in(std::string city) {
    person.m_city = city; 
    return *this;
}
```

<!-- wp:list -->
<ul><li>Rather stuffing all those construction related APIs into <code>Person</code>, we can delegate that task to separate entity i.e. <code>PersonBuilder</code>.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p><strong><code>Main.cpp</code></strong></p>
<!-- /wp:paragraph -->

```C++
#include <iostream>
#include "Person.h"
#include "PersonBuilder.h"
using namespace std;

int main()
{
    Person p = Person::create("John")
                                .lives()
                                    .at("123 London Road")
                                    .with_postcode("SW1 1GB")
                                    .in("London")
                                .works()
                                    .with("PragmaSoft")
                                    .as_a("Consultant")
                                    .earning("10e6");

    cout << p << endl;
    return EXIT_SUCCESS;
}
```

<!-- wp:list -->
<ul><li>Isn't the above construction looks more intuitive, natural & plain English?</li><li>If you are concerned about blank methods like <code>lives()</code> & <code>works()</code>, then do not worry, it will be eliminated in optimization.</li><li>You can also observe that we are forcing user's to use builder rather than constructor by making the constructor private & exposing only <code>create<strong>(</strong>std::string name<strong>)</strong></code> API.</li><li>Do not over complicate things by designing an interface or abstract classes unless you need it. I have seen this in many Builder Design Pattern Examples on Web. </li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Benefits of Builder Design Pattern</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>The number of lines of code increases at least to double in builder pattern. But the effort pays off in terms of design flexibility, fewer or no parameters to the constructor and much more readable code. </li><li>Builder Design Pattern also helps in minimizing the number of parameters in constructor & thus there is no need to pass in <a rel="noreferrer noopener" aria-label="null (opens in a new tab)" href="http://www.vishalchovatiya.com/what-exactly-nullptr-is-in-cpp/" target="_blank"><span style="color:#0002a3" class="color">null</span></a> for optional parameters to the constructor.</li><li>Immutable objects can be built without much complex logic in the object building process.</li><li>Segregating construction from <a rel="noreferrer noopener" aria-label="object representation (opens in a new tab)" href="http://www.vishalchovatiya.com/memory-layout-of-cpp-object/" target="_blank"><span style="color:#1c00a3" class="color">object representation</span></a> makes the object representation slice & precise. Having a builder entity separate provides the flexibility of creating & instantiating different objects representations.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Summary by FAQs</h2>
<!-- /wp:heading -->

<!-- wp:yoast/faq-block {"questions":[{"id":"faq-question-1586174463520","question":["When should the Builder Design Pattern be used?"],"answer":["Whenever creation of new object requires setting many parameters and some of them (or all of them) are optional."],"jsonQuestion":"When should the Builder Design Pattern be used?","jsonAnswer":"Whenever creation of new object requires setting many parameters and some of them (or all of them) are optional."},{"id":"faq-question-1586174665465","question":["Why do we need a Builder class when implementing a Builder Design Pattern?"],"answer":["It isn't necessary but there are some benefits in doing so:",{"type":"br","props":{"children":[]}},"- The concern of building object should be in the separate entity as per ",{"type":"a","props":{"rel":"noreferrer noopener","href":"http://www.vishalchovatiya.com/single-responsibility-principle-in-cpp-solid-as-a-rock/","target":"_blank","children":[{"type":"span","props":{"style":"color:#9b51e0","class":"color","children":["SRP"]}}]}},".",{"type":"br","props":{"children":[]}},"- The original object would not be bloated.",{"type":"br","props":{"children":[]}},"- Easy \u0026 maintainable code.",{"type":"br","props":{"children":[]}},"- Testing \u0026 understanding a constructor with many input arguments gets exponentially more complicated."],"jsonQuestion":"Why do we need a Builder class when implementing a Builder Design Pattern?","jsonAnswer":"It isn't necessary but there are some benefits in doing so:\u003cbr/\u003e- The concern of building object should be in the separate entity as per \u003ca rel=\u0022noreferrer noopener\u0022 href=\u0022http://www.vishalchovatiya.com/single-responsibility-principle-in-cpp-solid-as-a-rock/\u0022 target=\u0022_blank\u0022\u003e\u003cspan style=\u0022color:#9b51e0\u0022 class=\u0022color\u0022\u003eSRP\u003c/span\u003e\u003c/a\u003e.\u003cbr/\u003e- The original object would not be bloated.\u003cbr/\u003e- Easy \u0026amp; maintainable code.\u003cbr/\u003e- Testing \u0026amp; understanding a constructor with many input arguments gets exponentially more complicated."},{"id":"faq-question-1586174666311","question":["Greatest Advantage of Builder Design Pattern!"],"answer":["More expressive code.",{"type":"br","props":{"children":[]}},{"type":"code","props":{"children":["MyClass o = new MyClass(5, 5.5, 'A', var, 1000, obj9, \u0022hello\u0022);"]}},{"type":"br","props":{"children":[]}},"- Instead ",{"type":"br","props":{"children":[]}},{"type":"code","props":{"children":["MyClass o = MyClass.builder().a(5).b(5.5).c('A').d(var).e(1000).f(obj9).g(\u0022hello\u0022);"]}},{"type":"br","props":{"children":[]}},"- You can see which data member is being assigned by what \u0026 even change the order of assignment."],"jsonQuestion":"Greatest Advantage of Builder Deisgn Pattern!","jsonAnswer":"More expressive code.\u003cbr/\u003e\u003ccode\u003eMyClass o = new MyClass(5, 5.5, 'A', var, 1000, obj9, \u0022hello\u0022);\u003c/code\u003e\u003cbr/\u003e- Instead \u003cbr/\u003e\u003ccode\u003eMyClass o = MyClass.builder().a(5).b(5.5).c('A').d(var).e(1000).f(obj9).g(\u0022hello\u0022);\u003c/code\u003e\u003cbr/\u003e- You can see which data member is being assigned by what \u0026amp; even change the order of assignment."}]} -->
<div class="schema-faq wp-block-yoast-faq-block"><div class="schema-faq-section" id="faq-question-1586174463520"><strong class="schema-faq-question">When should the Builder Design Pattern be used?</strong> <p class="schema-faq-answer">Whenever creation of new object requires setting many parameters and some of them (or all of them) are optional.</p> </div> <div class="schema-faq-section" id="faq-question-1586174665465"><strong class="schema-faq-question">Why do we need a Builder class when implementing a Builder Design Pattern?</strong> <p class="schema-faq-answer">It isn't necessary but there are some benefits in doing so:<br/>- The concern of building object should be in the separate entity as per <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/single-responsibility-principle-in-cpp-solid-as-a-rock/" target="_blank"><span style="color:#9b51e0" class="color">SRP</span></a>.<br/>- The original object would not be bloated.<br/>- Easy & maintainable code.<br/>- Testing & understanding a constructor with many input arguments gets exponentially more complicated.</p> </div> <div class="schema-faq-section" id="faq-question-1586174666311"><strong class="schema-faq-question">Greatest Advantage of Builder Deisgn Pattern!</strong> <p class="schema-faq-answer">More expressive code.<br/><code>MyClass o = new MyClass(5, 5.5, 'A', var, 1000, obj9, "hello");</code><br/>- Instead <br/><code>MyClass o = MyClass.builder().a(5).b(5.5).c('A').d(var).e(1000).f(obj9).g("hello");</code><br/>- You can see which data member is being assigned by what & even change the order of assignment.</p> </div> </div>
<!-- /wp:yoast/faq-block -->



[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/)🖱️