Builder
What you will learn on this page
Section titled “What you will learn on this page”- The problem Builder solves, shown before the pattern is named: a constructor with many parameters, where swapped arguments compile and nothing checks how the parts fit together.
- How a builder collects the parts in any order, then checks all
the rules, including rules about combinations, in one
build(), so every finished object is valid. - How to sort a class’s data into required parts, optional parts with defaults, and values worked out from the others.
- The simpler tools to try first: distinct types, and C++20 designated initializers, which cover most cases.
The problem
Section titled “The problem”A team writes a small HTTP client library. Several services use it to call each other. Each call starts by making a request: what to send, where, and how patiently.
Requirements:
- FR-1 A request needs a method (GET, POST, PUT, DELETE) and a URL. Everything else is optional: headers, query parameters, a body with its content type, a timeout (30 s by default), a number of retries (0 by default), and whether to follow redirects (yes by default).
- FR-2 An invalid request never reaches the network. The rules:
- the URL starts with
http://orhttps://, names a host, and contains no spaces, control characters, user name or password, or fragment (#); - header names are letters, digits, and
-(a deliberate subset of what HTTP allows), and no header value contains a line break (a line break would let a value inject extra headers); Host,Content-Type, andContent-Lengthare worked out by the library, never set by hand;- a GET has no body (HTTP allows one but gives it no meaning, so this library refuses it), and a body has a content type;
- the timeout is positive, and retries are between 0 and 10;
- a POST is never retried: if the response is lost, a retry could place the same order twice. PUT and DELETE are idempotent (sending one twice has the same effect as sending it once), so they may be retried; POST is not.
- the URL starts with
- FR-3 A request, once made, stays valid. Code that receives one can send it without checking it again.
- FR-4 Code that makes a request is easy to read: each value is named where it is given.
- FR-5 When a request is invalid, the error lists every problem, so the caller can fix them in one go.
Where Builder shows up in requirements. Listen for “many optional settings, each with a default”, “rules between settings” (this one only if that one), “the object is assembled step by step” (from a config file, then the command line, then code), and “once made, it cannot change”. In code, the signal is a constructor with a long row of parameters, or a family of constructors for the common combinations. Builders come up less often in C++ than in Java or C#: as the rest of this page shows, plainer tools often do the job.
The straightforward solution
Section titled “The straightforward solution”Put every part in the constructor:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every part is a constructor parameter, in a fixed order.// The straightforward version: one constructor takes all seven parts and// stores them as given. It checks nothing, so any combination of values// makes a request, and a caller must remember which position means what.class HttpRequest final {public: // The strings and the vector are taken by value and then moved into // the members (std::move hands over their contents instead of copying // them a second time). The three numbers and the flag are just copied. HttpRequest(std::string method, std::string url, std::vector<Header> headers, std::string body, int timeout_ms, int max_retries, bool follow_redirects) : method_{std::move(method)}, url_{std::move(url)}, headers_{std::move(headers)}, body_{std::move(body)}, timeout_ms_{timeout_ms}, max_retries_{max_retries}, follow_redirects_{follow_redirects} {}
const std::string& method() const { return method_; } const std::string& url() const { return url_; } const std::vector<Header>& headers() const { return headers_; } const std::string& body() const { return body_; } int timeout_ms() const { return timeout_ms_; } int max_retries() const { return max_retries_; } bool follows_redirects() const { return follow_redirects_; }
private: std::string method_; std::string url_; std::vector<Header> headers_; std::string body_; int timeout_ms_; int max_retries_; bool follow_redirects_;};Two tests pin down what it allows:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, and LLD_CHECK_EQ(actual, expected) records a// failure, printing both values, if they differ. They come from the site's// small test header, lld_test.hpp. `orders` is a string defined at the top// of this file: "https://api.example.com/v1/orders".//// Seven positional parameters. Two are ints, and this call swaps them.// {{"Authorization", "Bearer t0k3n"}} is a vector holding one Header (the// outer braces make the vector, the inner ones the Header). R"(...)" is a// raw string literal: everything between the brackets is taken as written,// so the quotes inside need no backslashes.LLD_TEST(before_positional_arguments_compile_in_the_wrong_order) { const before::HttpRequest request{"PUT", orders + "/42", {{"Authorization", "Bearer t0k3n"}}, R"({"quantity": 2})", 3, 5000, true}; // The author meant a 5000 ms timeout and 3 retries. // The checks pass, which is the problem: the compiler accepted the swap, // and the request really has a 3 ms timeout and 5000 retries. LLD_CHECK_EQ(request.timeout_ms(), 3); LLD_CHECK_EQ(request.max_retries(), 5000);}
// Nothing checks the parts, alone or together.// The URL has no "https://", the GET has a body with no content type, and// the timeout is 0, yet the request is made and holds exactly those values.LLD_TEST(before_any_combination_is_accepted) { const before::HttpRequest request{"GET", "api.example.com/search", {}, "{}", 0, 0, true}; LLD_CHECK_EQ(request.method(), std::string{"GET"}); // a GET with a body, LLD_CHECK_EQ(request.body(), std::string{"{}"}); // no content type, LLD_CHECK_EQ(request.timeout_ms(), 0); // no scheme, and no time limit}- FR-4 fails. A call is a row of values; to read one, you count
commas.
3, 5000compiles whichever way round it is, because both parameters areint. The first test has a timeout of 3 ms and 5000 retries. - FR-2 fails. Nothing checks anything. A GET with a body, a URL without a scheme, and a zero timeout all make a request.
- FR-5 fails for the same reason: there is no error at all.
- FR-3 holds, but only vacuously: the request cannot change, but it may have been invalid from the start.
The usual first fix is telescoping constructors: one constructor for method and URL, another that adds headers, another that adds a body, and so on. With six optional parts, the useful combinations are far more than anyone wants to write, and every overload still takes its values by position. The other usual fix is a request with setters. Then a request is half-made between calls, the rules about combinations have no single place to run, and FR-3 is lost.
Step 1: sort the data and the functions
Section titled “Step 1: sort the data and the functions”Look at the request’s data and ask, for each part, when it is known and who should check it:
| Data or job | Kind | Where it goes |
|---|---|---|
| method, URL | required | the builder’s constructor, so they cannot be forgotten |
| headers, query parameters, body, timeout, retries, redirects | optional, with defaults | builder data members, empty or with a default value; one step function each |
host, target (path and query), Host, Content-Type, Content-Length |
worked out from the others | computed once, in build() |
| rules about one part (timeout > 0) | validation | build(), with the rest, so FR-5 can list every problem |
| rules about combinations (GET with a body) | validation | build(): only it knows that every step has been taken |
| the finished request | the product | HttpRequest: a value with getters only, created only by build() |
The table sorts the data members of two classes:
- The builder’s members are raw input: the URL as a string, the
body as an
std::optional, headers as given. Any value is allowed in them while the request is being assembled. - The request’s members are checked results: a host and a target
instead of a URL, and the full header list, including the headers
build()worked out. Every value in them has passed the rules.
The functions sort as well. The builder’s steps change it and
return it, so they can be chained. build() is a const member
function: it reads the steps’ results and creates a new object. The
request has only const getters, so nothing can break its rules later.
The pattern
Section titled “The pattern”Builder separates
assembling an object from the object itself. A builder object
collects the parts, in any order, through small, named steps (only
where the order is itself data, as with the order of headers, does it
show in the result); a final
build() checks them together and creates the finished object, which
is valid from the moment it exists.
The roles:
- Builder:
RequestBuilder, holding the parts collected so far. - Product:
HttpRequest, the finished, checked object. - Client: any code that builds a request:
main, the tests, andget, which builds a simple GET for its callers.
class RequestBuilder final
the builder
Data members
Method method_;requiredstd::string url_;required; raw, checked in build()std::vector<Header> headers_;in the order addedstd::vector<Header> query_;std::optional<Body> body_;a content type and the contentstd::chrono::milliseconds timeout_{30'000};int max_retries_ = 0;bool follow_redirects_ = true;
Member functions
RequestBuilder(Method method, std::string url);RequestBuilder& header(std::string name, std::string value);a step; also query, body, json, timeout, retries, ...HttpRequest build() const;checks every rule; throws std::invalid_argument
class HttpRequest final
the product: created only by build()
Data members
std::string host_;from the URLstd::string target_;path and query, encodedstd::vector<Header> headers_;includes Host, Content-Type, Content-Lengthstd::string body_;std::chrono::milliseconds timeout_;
Member functions
const std::vector<Header>& headers() const;getters only; also host, target, body, timeout, ...std::string to_text() const;as sent, HTTP/1.1
namespace global
not a real namespace: free functions at file scope
Functions
HttpRequest get(std::string url, const GetOptions& options = {});a client; designated initializers
The outline leaves out some of HttpRequest’s members (the method,
the retry count, and the redirect setting) and its private constructor.
Text description of the diagram
A solid arrow means “creates”, and a dashed arrow means “uses”. The client (main, get, or a test) takes steps on the RequestBuilder, such as header, json, and timeout; the builder holds the raw parts. The client calls build(). The builder checks every rule, then creates an HttpRequest, which is checked and cannot change. The client then uses the request’s getters and to_text.
Diagram source (Mermaid)
flowchart LR
CLIENT["client<br/>main, get, tests"] -.->|"steps: header,<br/>json, timeout, ..."| B["RequestBuilder<br/>raw parts"]
CLIENT -.->|"build()"| B
B -->|"checks every rule,<br/>then creates"| R["HttpRequest<br/>checked, cannot change"]
CLIENT -.->|"uses getters,<br/>to_text"| RThe C++ implementation
Section titled “The C++ implementation”The product
Section titled “The product”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A request that is ready to send. It has no public constructor: the// only way to get one is RequestBuilder::build(), which checks it, so// every HttpRequest is valid. It has getters and no setters, so it stays// valid.// This is the "product" of the Builder pattern: the finished object. It// is a plain value: it can be copied and moved like a string.class HttpRequest final {public: Method method() const { return method_; } // The host comes from the URL, e.g. "api.example.com". const std::string& host() const { return host_; } // The target is what follows the host, e.g. "/v1/orders/42?dry_run=true". const std::string& target() const { return target_; } // path and query const std::vector<Header>& headers() const { return headers_; } // includes Host const std::string& body() const { return body_; } // std::chrono::milliseconds is a length of time with its unit in the // type, so a timeout cannot be confused with a count of retries. std::chrono::milliseconds timeout() const { return timeout_; } int max_retries() const { return max_retries_; } bool follows_redirects() const { return follow_redirects_; }
// The request as text: a first line such as "PUT /v1/orders HTTP/1.1", // one "Name: value" line per header, an empty line, then the body. std::string to_text() const; // as sent on the wire, HTTP/1.1
private: // `friend` gives RequestBuilder access to the private members, in // particular to the constructor below. No other code can call it. friend class RequestBuilder; // Private: only RequestBuilder::build() creates requests, and it calls // this only after every check has passed. HttpRequest(Method method, std::string host, std::string target, std::vector<Header> headers, std::string body, std::chrono::milliseconds timeout, int max_retries, bool follow_redirects);
Method method_; std::string host_; std::string target_; std::vector<Header> headers_; std::string body_; std::chrono::milliseconds timeout_; int max_retries_; bool follow_redirects_;};- The constructor is private, and
RequestBuilderis afriend, sobuild()is the only way to create anHttpRequest. That is what makes FR-3 true: no code path makes an unchecked request. - Getters only. No member function changes a request after it is
built, so it stays valid. Two things remain possible, as for any
value: a non-
constrequest can be replaced as a whole by assigning another request to it, and a moved-from request is empty. Do not send a request after moving from it. - It is a plain value. It can be copied (to send the same request
twice) and moved, and
build()returns it by value. There is nostd::unique_ptrhere: unlike a factory, a builder of one concrete class has no derived types to hide.
The builder and its steps
Section titled “The builder and its steps”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Collects a request's parts in any order, then checks them all at once.// The builder is a separate, changeable object that holds the parts while// they are being chosen. Only build() turns them into an HttpRequest, and// only if every rule holds. The builder itself is an ordinary value: it can// be copied, which lets one partly set-up builder serve as a template.class RequestBuilder final {public: // The parts every request needs are constructor parameters, so they // cannot be forgotten. RequestBuilder(Method method, std::string url);
// Each step records one part and returns *this, so steps can be chained. // `*this` is the builder the step was called on, and the return type // RequestBuilder& is a reference to it (not a copy), so in // b.timeout(5s).retries(3) the second step runs on the same builder b. // header() and query() add one more entry each time they are called; // body(), json(), timeout(), and retries() replace the earlier value. RequestBuilder& header(std::string name, std::string value); RequestBuilder& bearer_token(const std::string& token); // the Authorization header RequestBuilder& query(std::string name, std::string value); RequestBuilder& body(std::string content_type, std::string content); RequestBuilder& json(std::string content); // body("application/json", content) RequestBuilder& timeout(std::chrono::milliseconds limit); RequestBuilder& retries(int count); RequestBuilder& no_redirects();
// Checks every rule, including rules about combinations of parts. // Throws std::invalid_argument listing every problem it found. The // builder is unchanged, so a part that a later step replaces (the body, // the timeout, the retry count) can be corrected and built again. // `const`: build() only reads the parts, so the builder keeps them. // It returns the request by value: the caller owns the new HttpRequest. HttpRequest build() const;
private: // A body and its content type always travel together, so they are // one small struct. struct Body { std::string content_type; std::string content; };
// The parts collected so far, as the steps recorded them. Nothing here // has been checked yet; that is build()'s job. Method method_; std::string url_; std::vector<Header> headers_; // in the order they were added std::vector<Header> query_; // name and value pairs, reusing Header // std::optional: empty until body() or json() is called, so "no body" // and "an empty body" are different things. std::optional<Body> body_; // The defaults for parts no step sets. 30'000 is 30000; the ' only // groups the digits for the reader. That is 30 seconds. std::chrono::milliseconds timeout_{30'000}; int max_retries_ = 0; bool follow_redirects_ = true;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every step below has the same shape: store one part in a member, then// `return *this;` so the next step can be chained on the same builder.// None of them checks anything; the URL is kept exactly as given.RequestBuilder::RequestBuilder(Method method, std::string url) : method_{method}, url_{std::move(url)} {}
// Adds one header at the end of the list; calling it twice adds two.// The name and value were taken by value, so std::move hands their// contents to the new Header instead of copying them again.RequestBuilder& RequestBuilder::header(std::string name, std::string value) { headers_.push_back({std::move(name), std::move(value)}); return *this;}
// A shortcut that writes the header in the one correct form, e.g.// "Authorization: Bearer t0k3n". It returns what header() returns: *this.RequestBuilder& RequestBuilder::bearer_token(const std::string& token) { return header("Authorization", "Bearer " + token);}
// Records one query parameter, unencoded; build() encodes it and adds it// to the URL's target as ?name=value or &name=value.RequestBuilder& RequestBuilder::query(std::string name, std::string value) { query_.push_back({std::move(name), std::move(value)}); return *this;}
// Sets (or replaces) the body: assigning to the std::optional fills it,// so body_ now holds a value. A second call overwrites the first.RequestBuilder& RequestBuilder::body(std::string content_type, std::string content) { body_ = Body{std::move(content_type), std::move(content)}; return *this;}
// One step that sets two parts that belong together: the content and its// content type.RequestBuilder& RequestBuilder::json(std::string content) { return body("application/json", std::move(content));}
// The last three steps replace one setting each.RequestBuilder& RequestBuilder::timeout(std::chrono::milliseconds limit) { timeout_ = limit; return *this;}
RequestBuilder& RequestBuilder::retries(int count) { max_retries_ = count; return *this;}
RequestBuilder& RequestBuilder::no_redirects() { follow_redirects_ = false; return *this;}- Required parts are constructor parameters. There is no default constructor, so a builder without a method and a URL does not compile.
- Each step returns
RequestBuilder&, the builder itself, so steps chain:.bearer_token(...).json(...).timeout(5s). Each step’s name says which value it sets, which is FR-4. This style is often called a fluent interface, or the named-parameter idiom. - Steps can set several parts together.
jsonsets the body and its content type in one call, andbearer_tokenwrites the header in the right form. A constructor cannot offer such shortcuts without more overloads. - Steps do not check. They record. The order of steps is free, so a rule like “a GET has no body” can only be checked when all steps are done.
build(): check everything, then create
Section titled “build(): check everything, then create”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Turns the recorded parts into a finished request, or refuses.// It works in two phases. First it assembles everything (host, target,// headers, body) while writing each broken rule into `problems` instead of// stopping at the first one. Then, only if `problems` is empty, it creates// the HttpRequest. Throws std::invalid_argument naming every problem, in// the order the checks run. Being const, it never changes the builder.HttpRequest RequestBuilder::build() const { std::vector<std::string> problems; // one entry per broken rule
// The host and the target (path and query) come from the URL. // A std::string_view is a read-only window onto url_'s characters: // searching and slicing it (substr) makes no copies. const std::string_view url = url_; // `start` is where the host begins: just after the scheme, which is 8 // characters for "https://" and 7 for "http://". 0 means "no scheme". std::size_t start = 0; if (url.starts_with("https://")) { start = 8; } else if (url.starts_with("http://")) { start = 7; } std::string host; std::string target = "/"; // used when the URL has no path at all if (start == 0) { problems.push_back("the URL must start with http:// or https://"); } else if (has_space_or_control(url) || url.find('#') != std::string_view::npos) { // A line break here would end the request line early and inject headers. problems.push_back("the URL must not contain spaces, control characters, or '#'"); } else { // The host runs from `start` to the first '/' or '?' after it. // find_first_of returns std::string_view::npos ("not found") when // there is neither; then end - start is a huge number, and substr // simply takes the rest of the URL as the host. const std::size_t end = url.find_first_of("/?", start); host = std::string{url.substr(start, end - start)}; // Everything from `end` on is the target. A URL such as // "https://a.example?x=1" has a query but no path, so a "/" is put // in front: the target becomes "/?x=1". if (end != std::string_view::npos) { target = url[end] == '?' ? "/" + std::string{url.substr(end)} : std::string{url.substr(end)}; } if (host.empty()) { problems.push_back("the URL has no host"); // e.g. "https:///search" } else if (host.find('@') != std::string::npos) { problems.push_back("the URL must not contain a user name or password"); } } // Append each query parameter to the target. The first separator is '?' // unless the target already has one (from the URL, or from an earlier // parameter); after that it is '&'. Encoding keeps a space, '&', or '=' // in a value from breaking the query apart: "a b" is sent as "a%20b". for (const Header& parameter : query_) { if (parameter.name.empty()) { problems.push_back("a query parameter needs a name"); } target += target.find('?') == std::string::npos ? '?' : '&'; target += percent_encoded(parameter.name) + '=' + percent_encoded(parameter.value); }
// Host, Content-Type, and Content-Length are worked out here, never set by hand. // The finished header list starts with Host, then the caller's headers // in the order they were added, then the two body headers. std::vector<Header> headers{{"Host", host}}; for (const Header& header : headers_) { // At most one problem about the name (the if / else if chain stops // at the first match), plus, separately, one about the value. // same_name ignores upper and lower case, so "content-type" is // caught as well as "Content-Type". if (!valid_name(header.name)) { problems.push_back("'" + header.name + "' is not a valid header name"); } else if (same_name(header.name, "Host") || same_name(header.name, "Content-Length")) { problems.push_back(header.name + " is set by build(), not by hand"); } else if (same_name(header.name, "Content-Type")) { problems.push_back("set Content-Type with body() or json()"); } // A line break in a value would let the rest of it be sent as an // extra header, as in "hi\r\nX-Admin: yes". if (has_line_break(header.value)) { problems.push_back("the value of header " + header.name + " contains a line break"); } headers.push_back(header); // a copy: build() must leave headers_ as it was } std::string content; // `if (body_)` is true when the optional holds a Body, that is, when // body() or json() was called. body_-> reaches the Body inside it. if (body_) { // A rule about a combination of two parts: the method and the body. if (method_ == Method::get) { problems.push_back("a GET request cannot have a body"); } if (body_->content_type.empty() || has_line_break(body_->content_type)) { problems.push_back("a body needs a content type on one line"); } headers.push_back({"Content-Type", body_->content_type}); // The length is counted here, from the content itself, so it is // always right: {"quantity": 2} is 15 characters, so "15". headers.push_back({"Content-Length", std::to_string(body_->content.size())}); content = body_->content; // copied, again so that the builder keeps its body }
// Rules about the other settings, alone and together. if (timeout_ <= std::chrono::milliseconds::zero()) { problems.push_back("the timeout must be positive"); } if (max_retries_ < 0 || max_retries_ > 10) { problems.push_back("retries must be between 0 and 10"); } // Retrying a POST could, for example, place the same order twice. if (max_retries_ > 0 && method_ == Method::post) { problems.push_back("a POST request is not idempotent, so it cannot be retried"); }
// Phase two. Any problem at all: throw one exception whose message // lists them all, joined with "; ". No HttpRequest is made. if (!problems.empty()) { throw std::invalid_argument{"cannot build the request: " + joined(problems, "; ")}; } // Every rule holds. build() may call the private constructor because // HttpRequest names RequestBuilder as a friend. host, target, headers, // and content are local variables that are not used again, so they are // moved into the request; the members of the builder are only read. return HttpRequest{method_, std::move(host), std::move(target), std::move(headers), std::move(content), timeout_, max_retries_, follow_redirects_};}How this code works: RequestBuilder::build
build() never stops at the first problem. Each check that fails adds a
sentence to the vector problems and carries on, so that the caller
learns about every mistake at once. Only at the end does it decide.
- Split the URL. If the URL starts with
https://orhttp://,startis the position just after it (8 or 7). The host runs from there to the first/or?, and everything from that character on is the target. A URL with a bad scheme, or with spaces, control characters, or#, is not split at all: the problem is recorded and the host stays empty. - Add the query parameters to the target, each percent-encoded,
with
?before the first one and&before the others. - Assemble the headers:
Hostfirst, then each header the caller added (checking its name and value), thenContent-TypeandContent-Lengthif there is a body. Copies go into the localheaders; the builder’s own list is left alone. - Check the remaining rules: the body against the method, the timeout, the retry count, and retries against the method.
- Decide. If
problemshas anything in it, throw onestd::invalid_argumentlisting all of them. Otherwise create theHttpRequestfrom the local values.
A worked example: the PUT in main. The builder holds the URL
https://api.example.com/v1/orders/42, one header from bearer_token,
one query parameter, a JSON body, a 5-second timeout, and 3 retries.
startis 8. The first/after it begins/v1, so the host isapi.example.comand the target/v1/orders/42.- The target has no
?yet, so it becomes/v1/orders/42?dry_run=true(letters and_are kept as they are). - The headers are
Host: api.example.com,Authorization: Bearer t0k3n,Content-Type: application/json, andContent-Length: 15, because{"quantity": 2}is 15 characters. - A PUT may have a body, 5000 ms is positive, 3 retries is within 0 to 10, and the method is not POST.
- No step added a problem, so
problemsis empty and the request is created. Its text is the first block of the output in the Check section.
The refused POST in main goes through the same steps. Its URL is
fine, but step 3 finds a line break in the value of X-Note, and step 4
finds a zero timeout and retries on a POST. So problems ends with three
entries, in that order, and the message is the one in the output:
cannot build the request: the value of header X-Note contains a line break; the timeout must be positive; a POST request is not idempotent, so it cannot be retried.
- It works out the derived values: the host and target from the
URL, the encoded query, and the
Host,Content-Type, andContent-Lengthheaders. Callers cannot get them wrong, because they cannot set them. - It treats the URL as untrusted text. A line break in the URL
would end the request line early, and the text after it would be
sent as extra headers, or as a second request. So
build()refuses spaces and control characters in the URL, as it refuses line breaks in header values. The URL rules here are a small subset; a real client should use a complete URL parser. - It collects every problem before throwing, so one error message lists them all (FR-5).
- It is
const. A failedbuild()leaves the builder as it was, so a part that a later step replaces, such as the body or the timeout, can be corrected and built again; a header or the URL cannot be taken back, so a mistake there needs a new builder. And a builder can serve as a template: copy it, add the parts that differ, and build each copy (a test below does this). - It throws
std::invalid_argument, because an invalid request is a mistake in the calling code, not a normal outcome. If invalid input were expected (requests read from user files, say), returning the list of problems instead of throwing would fit better.
The simpler alternative: designated initializers
Section titled “The simpler alternative: designated initializers”For one common case, a GET with a few settings, the library offers a function instead of a builder:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// For the common case, a GET with a few optional settings. Each field// has a default, and a designated initializer names the ones a caller// changes: get(url, {.timeout = 2s, .follow_redirects = false}).// The defaults are the same as the builder's: 30 seconds (30'000 ms, the// ' only groups digits), no retries, and redirects followed.struct GetOptions { std::chrono::milliseconds timeout{30'000}; int max_retries = 0; bool follow_redirects = true;};
// Throws std::invalid_argument, as RequestBuilder::build() does.// `= {}` is a default argument: get(url) on its own means "all defaults",// as if the caller had written get(url, GetOptions{}).HttpRequest get(std::string url, const GetOptions& options = {});VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The simple front door is built on the builder, so every GET made this// way passes the same checks in build(). The builder is a named local// variable, which is what makes the `if` in the middle possible: a step can// be applied or skipped, and the builder lives until the function returns.HttpRequest get(std::string url, const GetOptions& options) { RequestBuilder builder{Method::get, std::move(url)}; builder.timeout(options.timeout).retries(options.max_retries); // There is no step to turn redirects on (that is the default), so the // step is called only when the caller asked to turn them off. if (!options.follow_redirects) { builder.no_redirects(); } return builder.build();}A call reads get(url, {.timeout = 2s, .follow_redirects = false}):
each value is named (FR-4), the rest keep their defaults, and get
still checks everything, because it builds through RequestBuilder.
Two limits of designated initializers in C++20: the names must appear
in the order the members are declared (GCC 11 rejects a call that
reorders them; Clang 14 accepts it with a warning), and there is no
place for steps such as “add another header” or “set the body and its
type together”. When the options are a short, fixed list like this,
prefer the struct.
Ownership and lifetime
Section titled “Ownership and lifetime”| Object | Owner | Lives |
|---|---|---|
| a builder | whoever creates it; often a temporary | until the end of the statement, if a temporary; otherwise its scope |
| a part in the builder | the builder, by value (std::string, std::vector) |
as long as the builder |
| a built request | the caller, by value | independent of the builder; it copies or moves every part |
The builder stores its parts by value, and build() copies them
into the request. Neither keeps a pointer or a std::string_view into
the caller’s data, so a request stays valid after the strings it was
built from are gone, and after the builder is gone.
One request, step by step
Section titled “One request, step by step”Text description of the diagram
main creates a RequestBuilder with PUT and the URL. It calls bearer_token, query, and json; each step returns the builder for the next step. It calls timeout with 5 seconds and retries with 3. Then main calls build. The builder splits the URL, encodes the query, and adds the worked-out headers, then checks every rule and finds no problems. It creates the HttpRequest with the checked parts and returns it to main by value. main calls to_text on the request.
Diagram source (Mermaid)
sequenceDiagram
participant M as main
participant B as RequestBuilder
participant R as HttpRequest
M->>B: create with PUT and the URL
M->>B: bearer_token, query, json
B-->>M: the builder, for the next step
M->>B: timeout(5s), retries(3)
M->>B: build()
B->>B: split the URL, encode the query, add the worked-out headers
B->>B: check every rule, no problems found
B->>R: create with the checked parts
B-->>M: the request, by value
M->>R: to_text()VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// `using namespace std::chrono_literals;` (above this snippet) is what lets// 5s, 2s, and 0ms be written as durations.int main() { // One statement: make a temporary builder, chain the steps on it, and // finish with build(). The temporary lives until the end of the // statement, which is after build() has returned the finished request, // so this is safe. `update` is the request, not the builder. const HttpRequest update = RequestBuilder{Method::put, "https://api.example.com/v1/orders/42"} .bearer_token("t0k3n") .query("dry_run", "true") .json(R"({"quantity": 2})") .timeout(5s) .retries(3) .build(); std::cout << update.to_text() << '\n'; // .count() turns the duration into a plain number of milliseconds: // 5s becomes 5000. std::cout << "timeout " << update.timeout().count() << " ms, retries " << update.max_retries() << "\n\n";
// The designated initializer names only the options that change; // max_retries, not named, keeps its default of 0. const HttpRequest search = get("https://shop.example.com/search", {.timeout = 2s, .follow_redirects = false}); std::cout << search.to_text(); std::cout << "timeout " << search.timeout().count() << " ms, redirects " << (search.follows_redirects() ? "followed" : "not followed") << "\n\n";
// A request that breaks three rules: a line break in a header value, a // zero timeout, and retries on a POST. build() throws once, and the // message lists all three. The steps themselves accept every value. try { RequestBuilder{Method::post, "https://api.example.com/v1/orders"} .header("X-Note", "hi\r\nX-Admin: yes") .json("{}") .timeout(0ms) .retries(3) .build(); } catch (const std::invalid_argument& error) { std::cout << "error: " << error.what() << '\n'; }}PUT /v1/orders/42?dry_run=true HTTP/1.1Host: api.example.comAuthorization: Bearer t0k3nContent-Type: application/jsonContent-Length: 15
{"quantity": 2}timeout 5000 ms, retries 3
GET /search HTTP/1.1Host: shop.example.com
timeout 2000 ms, redirects not followed
error: cannot build the request: the value of header X-Note contains a line break; the timeout must be positive; a POST request is not idempotent, so it cannot be retriedRead the output against the requirements:
- The PUT request has
Host,Content-Type, andContent-Lengthheaders that no caller wrote, and the query was added to the target (FR-2). - The GET from
gethas the 2-second timeout and no redirects that its designated initializer named, and no body or extra headers (FR-1, FR-4). - The bad POST is refused with three problems in one message: the header value with a line break, the zero timeout, and the retries on a POST (FR-2, FR-5).
The tests check each rule, including the URL rules that stop a line break in the URL from injecting headers, that the steps can come in any order, and that a failed build leaves the builder usable:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Two helpers defined at the top of this file: problems_of(builder) calls// build() and returns the message of the std::invalid_argument it throws,// or "built" if it throws nothing; mentions(text, part) is true if `part`// appears somewhere in `text`. LLD_CHECK_THROWS(expression, type), used at// the end, fails the test unless the expression throws that type.//// static_assert is checked by the compiler, not when the tests run: if a// rule about the types ever stops holding, this file stops compiling.// is_constructible_v asks "could code outside the class call a constructor// with these argument types?"; for HttpRequest the answer must be no,// because its constructor is private.static_assert(!std::is_default_constructible_v<RequestBuilder>); // method and URL are requiredstatic_assert(!std::is_constructible_v<HttpRequest, Method, std::string, std::string, std::vector<Header>, std::string, std::chrono::milliseconds, int, bool>); // only build()static_assert(std::is_copy_constructible_v<HttpRequest>); // a built request is a value
// Proves build() works out the derived parts: the target from the URL, the// Host header, Content-Type from json(), and Content-Length from the body// ({"sku": "A1"} is 13 characters). The header order is fixed: Host, the// caller's headers, then the two body headers.LLD_TEST(build_assembles_the_whole_request) { const HttpRequest request = RequestBuilder{Method::post, orders} .bearer_token("t0k3n") .json(R"({"sku": "A1"})") .timeout(5s) .build(); LLD_CHECK_EQ(request.to_text(), std::string{"POST /v1/orders HTTP/1.1\n" "Host: api.example.com\n" "Authorization: Bearer t0k3n\n" "Content-Type: application/json\n" "Content-Length: 13\n" "\n" R"({"sku": "A1"})"}); LLD_CHECK(request.timeout() == 5000ms); LLD_CHECK_EQ(request.max_retries(), 0); // the defaults apply to what was not set LLD_CHECK(request.follows_redirects());}
// The same three steps in two different orders give the same request,// because build() decides the layout, not the order of the steps. (Two// header() calls would still keep the order in which they were made.)LLD_TEST(the_steps_can_come_in_any_order) { const HttpRequest a = RequestBuilder{Method::put, orders + "/7"}.json("{}").retries(2).bearer_token("t").build(); const HttpRequest b = RequestBuilder{Method::put, orders + "/7"}.bearer_token("t").retries(2).json("{}").build(); LLD_CHECK_EQ(a.to_text(), b.to_text());}
// Four rules broken at once: no http(s) scheme, a body on a GET, a zero// timeout, and 11 retries. One message lists all four, in the order in// which build() checks them.LLD_TEST(build_reports_every_problem_at_once) { RequestBuilder builder{Method::get, "ftp://files.example.com"}; builder.json("{}").timeout(0ms).retries(11); LLD_CHECK_EQ(problems_of(builder), std::string{"cannot build the request: the URL must start with http:// or " "https://; a GET request cannot have a body; the timeout must be " "positive; retries must be between 0 and 10"});}
// One rule per check: each builder breaks exactly one rule, and the check// looks for that rule's words in the message. The URL rules come first;// the "\r\n" case is a header-injection attempt through the URL. The last// check is the counterpart of the POST rule: a PUT may be retried.LLD_TEST(build_checks_each_part_and_each_combination) { LLD_CHECK(mentions(problems_of(RequestBuilder{Method::get, "https:///search"}), "no host")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::get, "https://a.example\r\nX-Admin: yes"}), "must not contain spaces, control characters")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::get, "https://a.example/s#top"}), "'#'")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::get, "https://user:pw@a.example/"}), "user name or password")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::put, orders}.header("Content-Length", "1")), "Content-Length is set by build()")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::put, orders}.body("text/plain\nX: 1", "a")), "content type on one line")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::get, orders}.retries(-1)), "between 0 and 10")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::get, orders}.header("Host", "x")), "Host is set by build()")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::put, orders}.header("content-type", "x")), "set Content-Type with body() or json()")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::get, orders}.header("X Y", "1")), "not a valid header name")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::get, orders}.header("X-A", "1\nX-B: 2")), "line break")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::put, orders}.body("", "data")), "content type")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::get, orders}.query("", "1")), "query parameter needs a name")); LLD_CHECK(mentions(problems_of(RequestBuilder{Method::post, orders}.retries(1)), "POST request is not idempotent")); LLD_CHECK_EQ(problems_of(RequestBuilder{Method::put, orders}.retries(1)), std::string{"built"});}
// build() is const, so the throw changes nothing: the same builder, with// the timeout step called again with a valid value, then builds.LLD_TEST(a_failed_build_leaves_the_builder_ready_to_fix) { RequestBuilder builder{Method::get, orders}; builder.timeout(0ms); LLD_CHECK_THROWS(builder.build(), std::invalid_argument); builder.timeout(1s); LLD_CHECK(builder.build().timeout() == 1000ms);}
// The URL has a query but no path, so build() puts "/" in front of it.LLD_TEST(a_url_without_a_path_gets_the_root_path) { const HttpRequest request = RequestBuilder{Method::get, "https://a.example?x=1"}.build(); LLD_CHECK_EQ(request.host(), std::string{"a.example"}); LLD_CHECK_EQ(request.target(), std::string{"/?x=1"});}
// The URL already has "?page=2", so the new parameter is joined with '&'.// In its value, each space becomes %20 and '&' becomes %26 (their codes in// hexadecimal), so the '&' cannot be mistaken for a new parameter. A URL// with no path and no query gets the target "/".LLD_TEST(query_values_are_percent_encoded) { const HttpRequest request = RequestBuilder{Method::get, "https://shop.example.com/search?page=2"} .query("q", "blue shoes & socks") .build(); LLD_CHECK_EQ(request.target(), std::string{"/search?page=2&q=blue%20shoes%20%26%20socks"}); const HttpRequest root = RequestBuilder{Method::get, "https://example.com"}.build(); LLD_CHECK_EQ(root.target(), std::string{"/"});}
// RequestBuilder{authorized} makes a temporary copy of the set-up builder;// the query step changes only that copy, and build() ends the statement.// So `authorized` itself never gains a query parameter.LLD_TEST(one_builder_can_serve_as_a_template_for_several_requests) { RequestBuilder authorized{Method::get, orders}; authorized.bearer_token("t0k3n").timeout(2s); const HttpRequest first = RequestBuilder{authorized}.query("page", "1").build(); const HttpRequest second = RequestBuilder{authorized}.query("page", "2").build(); LLD_CHECK_EQ(first.target(), std::string{"/v1/orders?page=1"}); LLD_CHECK_EQ(second.target(), std::string{"/v1/orders?page=2"}); const HttpRequest plain = authorized.build(); LLD_CHECK_EQ(plain.target(), std::string{"/v1/orders"}); // the template is unchanged}
// get with no options uses every default (30 s, redirects followed); with// a designated initializer, only the named options change. A URL with no// scheme throws, because get builds through RequestBuilder::build().LLD_TEST(get_takes_named_options_with_defaults) { const HttpRequest plain = get("https://example.com/status"); LLD_CHECK(plain.timeout() == 30s); LLD_CHECK(plain.follows_redirects()); const HttpRequest quick = get("https://example.com/status", {.timeout = 2s, .max_retries = 1}); LLD_CHECK(quick.timeout() == 2s); LLD_CHECK_EQ(quick.max_retries(), 1); LLD_CHECK_THROWS(get("example.com/status"), std::invalid_argument);}When to use it
Section titled “When to use it”Use a builder when:
- an object has many optional parts, and the parts accumulate (headers, rows, children) or come from several places;
- some rules are about combinations of parts, so they can only be checked when everything is known;
- the finished object should be valid and unchanging from the moment it exists;
- convenience steps that set several parts together would make callers clearer.
Prefer something simpler when:
- every part is required: use a constructor, with distinct types for values that could be swapped;
- the options are a short, fixed list with defaults, and the rules are simple: use a struct with a designated initializer, and check it in the function or constructor that takes it.
- A second class with nearly the same data members as the product. Adding a part means adding it to both, plus a step.
- Errors at run time. A missing required part is a compile error
only if it is a constructor parameter; every rule in
build()is found when the code runs. Tests must cover the builders your code uses. - A dangling-reference trap with chained steps on a temporary, as in the warning above.
Common misuse
Section titled “Common misuse”- A builder for a small struct.
PointBuilder().x(1).y(2).build()isPoint{.x = 1, .y = 2}with extra steps. - A
build()that checks nothing. Then the builder is a set of setters with a longer name, and FR-3 is not true. - Required parts as steps, checked only in
build(). A forgotten URL is then a run-time error, when it could have been a compile error. Make required parts constructor parameters. - A product with setters. If
HttpRequesthadset_timeout, code could undobuild()’s checks after the fact. - A builder that stores views or pointers into the caller’s data
(
std::string_viewparts). The builder, or the product, can then outlive the strings it points to. Store parts by value.
When the requirements change
Section titled “When the requirements change”- “Every request must name the calling service.” A new required part: see the exercise.
- “Settings come from a config file, then the command line can
override them.” A builder handles this well: read the file into a
builder, apply the command-line steps to the same builder, then call
build()once. - “Send the same request to three mirrors.” Copying a template
builder does not help here, because the URL is a constructor
parameter and a copy cannot change it. Either add a step that
replaces the URL, or put the shared steps in a function, such as
void add_common_parts(RequestBuilder&), and call it on a new builder for each mirror. - “Report problems to the user instead of throwing.” Add a
function that returns the list of problems (for example,
std::vector<std::string> problems() const) and havebuild()call it, so both use the same rules. See errors and contracts for choosing between the two.
Exercise
Section titled “Exercise”Exercise: Add a required field
Every request must now name the service that sends it, as an
X-Client header (for example, X-Client: billing), so the server’s
logs show who called.
- Where should the client name go in the builder, and why? Write the change.
- A teammate suggests a
client(std::string)step, and a check inbuild()that it was called. Compare that with your answer. - How should
build()treat a caller who also adds anX-Clientheader by hand? - Another teammate’s code crashes in testing:
RequestBuilder& b = RequestBuilder{Method::get, url, "billing"}.timeout(1s);followed, on the next line, bysend(b.build());. Explain, and fix it.
Show the explained answer
1. A required part belongs in the constructor:
// A third constructor parameter, beside the method and the URL: a builder// cannot be made without a client name.RequestBuilder(Method method, std::string url, std::string client);// ...std::string client_; // sent as X-Client
// request_builder.cpp// Taken by value and moved into the member, like the URL.RequestBuilder::RequestBuilder(Method method, std::string url, std::string client) : method_{method}, url_{std::move(url)}, client_{std::move(client)} {}
// in build(), right after the Host header:// valid_name allows only letters, digits, and '-', and refuses an empty// string, so an empty client, or one with a space or a line break, is// recorded as a problem.if (!valid_name(client_)) { problems.push_back("the client name must be letters, digits, and '-'");}headers.push_back({"X-Client", client_});Every existing RequestBuilder{...} now fails to compile until it
names its client. That is the point: the compiler finds every place
that makes a request, and none can be missed. get needs the client
too, as a parameter or as a field of GetOptions. A plain
std::string field can be left out of a designated initializer
without an error (GCC warns with -Wextra; Clang 14 does not), so
either use a parameter, or give the field a small type with no default
constructor, such as a ClientName class, which makes leaving it out
a compile error. An empty name still compiles, so build() checks the
value.
2. A step plus a check finds a forgotten client only when that code runs, and only if a test happens to run it. It is the right choice only if most callers should not have to care, for example when the library can supply a sensible default; then it is an optional part, not a required one.
3. As it treats Host: the library writes the header, so a
hand-written one is a problem. Add X-Client to the list of names that
are “set by build(), not by hand”. Header names are case-insensitive,
so x-client must be refused too, which same_name already handles.
4. The steps return a reference to the builder, and the builder is
a temporary that is destroyed at the end of the first statement. b
dangles, and b.build() is undefined behaviour. Either build in the
same statement
(send(RequestBuilder{Method::get, url, "billing"}.timeout(1s).build());),
or name the builder:
// A named builder lives until the end of the enclosing block, so it is// still there when build() is called on the third line.RequestBuilder builder{Method::get, url, "billing"};builder.timeout(1s);send(builder.build());Related patterns
Section titled “Related patterns”- Factory Method and Abstract Factory: a factory chooses which class to create; a builder assembles one class from many parts. They combine: a factory function can return a builder already set up for one service. See Factory Method and Abstract Factory.
- Prototype: copying a configured builder and changing a few parts is close to Prototype’s idea of making new objects by copying a configured one. See Prototype.
- Factory Method vs Abstract Factory vs Builder compares the three creational patterns.
Summary
Section titled “Summary”- A builder collects an object’s parts through named steps, in any
order, and checks them together in
build(), so every finished object is valid. - Required parts are constructor parameters; optional parts are
steps with defaults; values that follow from other parts are worked
out in
build(). - The product has a private constructor and getters only, and is returned by value.
- Do not keep a reference into a chain of steps on a temporary.
- Try distinct types and designated initializers first; reach for a builder when parts accumulate, steps set several parts, or rules span parts.