////
Copyright (c) 2024 The C++ Alliance, Inc. (https://cppalliance.org)

Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

Official repository: https://github.com/boostorg/website-v2-docs
////
= Design Best Practices
:navtitle: Best Practices

Use these guidelines as recommendations based on past author's experiences of preparing content for a library submission. 

* <<Overview>>
* <<Source Files>>
* <<Naming>>
* <<Testing and Error Handling>>
* <<Redirection>>
* <<Rationale>>
* <<Good and Less-Good Examples of API Design>>
* <<See Also>>


== Overview

When designing a new library:

* Aim first for clarity and correctness; optimization should be only a secondary concern in most Boost libraries.

* Aim for ISO Standard pass:[C++]. Than means making effective use of the standard features of the language, and avoiding non-standard compiler extensions. It also means using the https://en.cppreference.com/w/cpp/standard_library[Standard Library] where applicable.

* Headers should be good neighbors. See xref:design-guide/headers.adoc[] and <<Naming Consistency>>.

* Follow quality programming practices. Recommended texts include  _Effective pass:[C++] 2nd Edition_ and _More Effective pass:[C++]_, both by Scott Meyers and published by Addison Wesley.

* Use the pass:[C++] Standard Library or other Boost libraries, but only when the benefits outweigh the costs. Except in special cases, do not use libraries other than the pass:[C++] Standard Library or Boost.

* Read xref:user-guide:ROOT:implementation-variations.adoc[Implementation Variation Techniques] to see how to supply performance, platform, or other implementation variations.

* Read the guidelines for xref:design-guide/separate-compilation.adoc[Separate Compilation], to see how to ensure that compiled link libraries meet user expectations.

== Source Files

* Begin all source files (including programs, headers, scripts, etc.) with:

  . A comment line describing the contents of the file.

  . Comments describing copyright and licensing: again, refer to xref:requirements/license-requirements.adoc[]. Note that developers are allowed to provide a copy of the license text in LICENSE_1_0.txt, LICENSE.txt or LICENSE file within repositories of their libraries.
  
  . A comment line referencing your library on the Boost web site. For example:`// See https://www.boost.org/libs/foo` for library home page.
+
Where foo is the directory name (see below) for the library. As well as aiding users who come across a Boost file detached from its documentation, some of Boost's automatic tools depend on this comment to identify which library header files belong to.

* Although some Boost members use proportional fonts, tabs, and unrestricted line lengths in their own code, Boost's widely distributed source code should follow more conservative guidelines:

  . Use fixed-width fonts. See <<Source Code Fonts Rationale>>.

  . Use spaces rather than tabs. See <<Tabs Rationale>>.

  . Limit line lengths to 80 characters.

* End all documentation files (HTML or otherwise) with a copyright message and a licensing message. Refer to published library documentation for examples.

== Naming

Use the naming conventions of the pass:[C++] Standard Library (See <<Naming Conventions Rationale>>):

* Names (except as noted below) should be all lowercase, with words separated by underscores.

* Acronyms should be treated as ordinary names (e.g. xml_parser instead of XML_parser).

* Template parameter names begin with an uppercase letter.

* Macro names all uppercase and begin with BOOST_.

* Choose meaningful names - explicit is better than implicit, and readability counts. There is a strong preference for clear and descriptive names, even if lengthy.

=== Naming Consistency

As library developers and users have gained experience with Boost, the following consistent naming approach has come to be viewed as helpful, particularly for larger libraries that need their own header subdirectories and namespaces.

* The library is given a name that describes the contents of the library. Cryptic abbreviations are strongly discouraged. Following the practice of the pass:[C++] Standard Library, names are usually singular rather than plural. For example, a library dealing with file systems might chose the name "filesystem", but not "filesystems", "fs" or "nicecode".

* The library's primary directory (in parent *boost-root/libs*) is given that same name. For example, *boost-root/libs/filesystem*.

* The library's primary header directory (in *boost-root/libs/name/include*) is given that same name. For example, *boost-root/libs/filesystem/boost/filesystem*.

* The library's primary namespace (in parent *::boost*) is given that same name, except when there's a component with that name (e.g., *boost::tuple*), in which case the namespace name is pluralized. For example, *::boost::filesystem*.

* The first letter of the library name is capitalized.

* A period between "Boost" and the library name (e.g., Boost.Bind) is used if and only if the library name is not followed by the word "library".

* The word "library" is not part of the library name and is therefore lowercased.

Here are a few example sentences of how to apply these conventions:

[circle]
- "Boost.Bind was written by Peter Dimov."
- "The Boost Asio library was written by Christopher Kohlhoff."
- "I regularly use Spirit, a Boost library written by Joel de Guzman and Hartmut Kaiser."

=== Filenames

Naming requirements ensure that file and directory names are relatively portable, including to ISO 9660:1999 (with extensions) and other relatively limited file systems. Superscript links are provided to detailed rationale for each choice.

* Names must contain only lowercase ASCII letters ('a'-'z'), numbers ('0'-'9'), underscores ('_'), hyphens ('-'), and periods ('.'). Spaces are not allowed. 
** Some legacy file systems require single-case names. Single-case names eliminate casing mistakes when moving from case-insensitive to case-sensitive file systems.
** To quote the POSIX standard, "Filenames should be constructed from the portable filename character set because the use of other characters can be confusing or ambiguous in certain contexts."

* Directory names must not contain periods ('.').
** Strict implementations of ISO 9660:1999 and some legacy operating systems prohibit dots in directory names. The need for this restriction is fading, and may be removed in time.

* The first and last character of a file name must not be a period ('.').
** POSIX has special rules for names beginning with a period. Windows prohibits names ending in a period.

* The first character of names must not be a hyphen ('-'), as this would be too confusing or ambiguous in certain contexts.

* The maximum length of directory and file names is 31 characters. We had to draw the line somewhere, and so the limit imposed by a now obsolete Apple file system was chosen years ago.

* The total path length must not exceed 207 characters (ISO 9660:1999).

Other conventions ease communication:

* Files intended to be processed by a pass:[C++] compiler as part of a translation unit should have a three-letter filename extension ending in "pp" (typically `.cpp` and `.hpp`). Other files should not use extensions ending in "pp". This convention makes it easy to identify all of the source in Boost.

* All libraries have at their highest level a primary directory named for the particular library. See <<Naming Consistency>>. The primary directory may have sub-directories.


== Testing and Error Handling

* Provide sample programs or confidence tests so potential users can see how to use your library.

* Provide a regression test program or programs which follow the xref:testing/test-policy.adoc[].

* Use exceptions to report errors where appropriate, and write code that is safe in the face of exceptions.

* Avoid exception-specifications. See <<Exception Specification Rationale>>.

=== Assertions

It is recommended you add runtime assertions to your code (including library headers). Avoid C's `assert` macro and use Boost's `BOOST_ASSERT` macro (in boost/assert.hpp) instead as it is more configurable. 

Make sure your code compiles in the presence of the `min()` and `max()` macros. Some platform headers define `min()` and `max() ` macros which cause some common pass:[C++] constructs to fail to compile. To protect your code from inappropriate macro substitution:

* If you want to call `std::min()` or `std::max()`: 

  ** If you do not require argument-dependent look-up, use `(std::min)(a,b)`.

  ** If you do require argument-dependent look-up, you should:

    . `#include <boost/config.hpp>`

    . Use `BOOST_USING_STD_MIN();` to bring `std::min()` into the current scope.

    . Use min `BOOST_PREVENT_MACRO_SUBSTITUTION (a,b);` to make an argument-dependent call to `min(a,b)`.

* If you want to call `std::numeric_limits<int>::max()`, use `(std::numeric_limits<int>::max)()` instead.

* If you want to call a `min()` or `max()` member function, instead of doing `obj.min()`, use `(obj.min)()`.

* If you want to declare or define a function or a member function named `min` or `max`, then you must use the `BOOST_PREVENT_MACRO_SUBSTITUTION` macro. Instead of writing `int min() { return 0; }` you should write `int min BOOST_PREVENT_MACRO_SUBSTITUTION () { return 0; }`. This is true regardless if the function is a free (namespace scope) function, a member function or a static member function, and it applies for the function declaration as well as for the function definition.

[#redirection]
== Redirection

The primary directory should always contain a file named `index.html`. Authors have requested this so that they can publish URL's in the form `https://www.boost.org/libs/lib-name` with the assurance a documentation reorganization won't invalidate the URL. Boost's internal tools are also simplified if a library's documentation is always reachable via the simplified URL.

The primary directory `index.html` file should do an automatic redirection to the `doc/html` subdirectory. For example, the `json` library contains the following `index.html` file:

[source,html]
----
<html>
    <head>
        <title>Boost.JSON</title>
        <meta http-equiv="refresh" content="0; URL=./doc/html/index.html">
    </head>
    <body>
        Automatic redirection failed, please go to
        <a href="./doc/html/index.html">./doc/html/index.html</a>
        <hr>
        <tt>
        Boost.JSON<br>
        <br>
        Copyright&nbsp;(C)&nbsp;2019&nbsp;Vinnie&nbsp;Falco<br>
        Copyright&nbsp;(C)&nbsp;2020&nbsp;Krystian&nbsp;Stasiowski<br>
        <br>
        Distributed under the Boost Software License, Version 1.0.
        (See accompanying file LICENSE_1_0.txt or copy at
        <a href=http://www.boost.org/LICENSE_1_0.txt>http://www.boost.org/LICENSE_1_0.txt</a>) <br>
        <br>
        </tt>
    </body>
</html>
----

== Rationale

Rationale is defined as "The fundamental reasons for something; basis" by the American Heritage Dictionary.

Beman Dawes comments: _"Failure to supply contemporaneous rationale for design decisions is a major defect in many software projects. Lack of accurate rationale causes issues to be revisited endlessly, causes maintenance bugs when a maintainer changes something without realizing it was done a certain way for some purpose, and shortens the useful lifetime of software."_

Rationale is fairly easy to provide at the time decisions are made, but hard to accurately recover even a short time later. Rationale for some of the requirements and guidelines follows.

=== Exception Specification Rationale

Exception specifications (ISO 15.4) are sometimes coded to indicate what exceptions may be thrown, or because the programmer hopes they will improve performance. But consider the following member from a smart pointer:

[source,cpp]
----
T& operator*() const throw()  { return *ptr; }
----

This function calls no other functions; it only manipulates fundamental data types like pointers Therefore, no runtime behavior of the exception-specification can ever be invoked. The function is completely exposed to the compiler; indeed it is declared inline. Therefore, a smart compiler can easily deduce that the functions are incapable of throwing exceptions, and make the same optimizations it would have made based on the empty exception-specification. A "dumb" compiler, however, may make all kinds of pessimizations.

For example, some compilers turn off inlining if there is an exception-specification. Some compilers add try/catch blocks. Such pessimizations can be a performance disaster which makes the code unusable in practical applications.

Although initially appealing, an exception-specification tends to have consequences that require very careful thought to understand. The biggest problem with exception-specifications is that programmers use them as though they have the effect the programmer would like, instead of the effect they actually have.

A non-inline function is the one place a "throws nothing" exception-specification may have some benefit with some compilers.

=== Naming Conventions Rationale

The pass:[C++] standard committee's Library Working Group discussed this issue in detail, and over a long period of time. The discussion was repeated again in early Boost postings. A short summary:

* Naming conventions are contentious, and although several are widely used, no one style predominates.

* Given the intent to propose portions of Boost for the next revision of the pass:[C++] Standard Library, Boost decided to follow the Standard Library's conventions.

* Once a library settles on a particular convention, a vast majority of stakeholders want that style to be consistently used.

=== Source Code Fonts Rationale

Dave Abrahams comments: "An important purpose (I daresay the primary purpose) of source code is communication: the documentation of intent. This is a doubly important goal for Boost, I think. Using a fixed-width font allows us to communicate with more people, in more ways (diagrams are possible) right there in the source. Code written for fixed-width fonts using spaces will read reasonably well when viewed with a variable-width font, and as far as I can tell every editor supporting variable-width fonts also supports fixed width. I don't think the converse is true".

=== Tabs Rationale

Tabs are banned because of the practical problems caused by tabs in multi-developer projects like Boost, rather than any dislike in principle. See mailing list archives. Problems include maintenance of a single source file by programmers using tabs and programmers using spaces, and the difficulty of enforcing a consistent tab policy other than just "no tabs". Discussions concluded that Boost files should either all use tabs, or all use spaces, and thus the decision to stick with spaces for indentation.

=== ECMAScript/JavaScript Rationale

ECMAScript/JavaScript use is allowed but discouraged. Before the 1.29.0 release, two Boost libraries added ECMAScript/JavaScript documentation. Controversy followed (see mailing list archives), and the developers were asked to remove the ECMAScript/JavaScript. Reasons given for banning included:

* Incompatible with some older browsers and some text based browsers.

* Makes printing docs pages difficult.

* Often results in really bad user interface design.

* Would require Boost to test web pages for ECMAScript/JavaScript compliance.

* Makes docs maintenance by other than the original developer more difficult.

Consider those reasons if you decide that JavaScript is something you must use. In particular keep in mind that the Boost community is not responsible for testing your use of JavaScript. And hence it is up to you to ensure that the above issues are fully resolved in your use case.

=== Acknowledgements Rationale

As a library matures, it almost always accumulates improvements suggested to the authors by other Boost members. It is a part of the culture of boost.org to acknowledge such contributions, identifying the person making the suggestion. Major contributions are usually acknowledged in the documentation, while minor fixes are often mentioned in comments within the code itself.

== Good and Less-Good Examples of API Design

The following section provides examples of good and not-so-good API design, with examples.

=== Class Sizes

A class should represent one concept (for example `boost::filesystem::path`, `boost::asio::ip::address`, `boost::gregorian::date`). Avoid “god objects” that know or do everything. If a class has too many unrelated members, split into smaller classes or helpers. If more than seven private members, ask: “should this be two classes?”, and if a class requires long docs to explain, maybe the abstraction is too fat.

Most Boost classes behave like values, not like heavy opaque handles: copyable, movable, comparable, assignable. This makes them easy to store in containers and pass by value.

Keep private data small and tightly scoped. Avoid storing things that can be recomputed cheaply.

If something doesn't need state, make it a free function or template, not a class. Boost prefers non-member functions when possible (for example `boost::algorithm::to_upper_copy` vs. a string utility class).

Classes don't usually embed “last error” members. Errors are surfaced via exceptions, or dual APIs with `error_code&`.

=== Namespaces

Namespaces in pass:[C++] are a balancing act - they prevent name collisions (especially in template-heavy libraries), they clarify context (`boost::asio::ip::tcp::socket` is very precise), but they can get verbose and intimidating for new users.

The rule of thumb for namespaces is to have a single obvious point of entry, with a namespace depth of no more than three. If you need more, consider grouping with traits or helper classes instead of new namespaces.

Consider using inline namespaces for versioning, as they are useful when evolving APIs without breaking existing code.

Repetition does not work well with namespaces, if a higher namespace already disambiguates the purpose, keep lower level namespace names short.

Implementation details can be encapsulated in a `detail` namespace, such as `boost::asio::detail`, and all entries in the detail namespace should be `private`.

Namespaces should reflect what the user thinks about, not how you implemented it.

[cols="1,1",options="header",stripes=even,frame=none]
|===
| *Less-Good* | *Good* 
| `boost::asio::detail::socket_ops`
| `boost::asio::ip`
| `boost::filesystem::filesystem_error`
| `boost::filesystem::error`
|===

=== Clear Overloads

It is easier to understand multiple clear, simple overloads instead of one monster function.

[cols="1,1",options="header",stripes=even,frame=none]
|===
| *Less-Good* | *Good* 
| `remove(const path& p, bool recursive, bool force, bool follow_symlinks, ...);`
|
`boost::filesystem::remove("file.txt");            // simple
boost::filesystem::remove_all("dir");              // recursive
boost::filesystem::remove(path("file.txt"), ec);   // with error_code`
| `connect(host, port, use_ssl, timeout, retries, verbose, follow_redirects);`
| `connect(host, port);                     // minimal
connect(host, port, connection_options); // advanced`
|===

=== Option Objects

Group each concern into option objects, which are practically self-documenting, extensible, and avoids parameter overload. Boolean parameters in particular quickly become unreadable (`true, false, true`). Wrap them in option types.

[cols="1,1",options="header",stripes=even,frame=none]
|===
| *Less-Good* | *Good* 
|
`socket::set_options(...parameters...);`
|
`boost::asio::ip::tcp::socket socket(io_context);
socket.set_option(boost::asio::ip::tcp::no_delay(true));
socket.set_option(boost::asio::socket_base::reuse_address(true));
socket.set_option(boost::asio::socket_base::linger(true, 30));`

|===

=== Flexible Constructors

Clear constructors, each handling one case. Use factory functions for anything fancy.

[cols="1,1",options="header",stripes=even,frame=none]
|===
| *Less-Good* | *Good* 
|
`date(int year, int month, int day, int calendar_type, int offset, bool validate, ...);`
|
`boost::gregorian::date d1(2025, 9, 6);
boost::gregorian::date d2 = boost::gregorian::from_simple_string("2025-09-06");`

|===


=== Attribute-Based Configuration

Named keyword parameters (via `boost::parameter`) give clarity without giant parameter lists.

[cols="1,1",options="header",stripes=even,frame=none]
|===
| *Less-Good* | *Good* 
|
`log.add_file_log(...parameters...);`
|
`boost::log::add_file_log(
boost::log::keywords::file_name = "sample_%N.log",
boost::log::keywords::rotation_size = 10 * 1024 * 1024,
boost::log::keywords::format = "[%TimeStamp%] <%Severity%>: %Message%");`
| `parse(argc, argv, true, true, true, "default.cfg");`
| `po::options_description desc("Options");
desc.add_options()
("help", "Show help")
("config", po::value<std::string>(), "Config file");
po::store(po::parse_command_line(argc, argv, desc), vm);`

|===

=== Handling Errors

Allow both exception-throwing and error_code style.

[cols="1,1",options="header",stripes=even,frame=none]
|===
| *Less-Good* | *Good* 
|
`file f("data.txt");   // throws only`
|
`file f("data.txt", ec);   // no-throw version`

|===


=== Return Values

Return the result directly if there is only one natural result. Use output parameters (or error_code) only when performance matters (avoiding temporaries), or multiple results must be returned. Avoid returning `int` or `bool` for multi-state results. Use enums, optionals, variants to make meaning clear.

When algorithms partially consume input, returns iterators to mark progress, for example the following calls return iterators and not counts: `boost::sregex_iterator it(text.begin(), text.end(), pattern);` and `auto new_end = boost::remove(vec, 42);`. Another example of returning a more complex object is the use of _lazy proxy objects_ that behave like containers but defer computation. This enables zero-cost abstraction and makes pipelines composable. An example is `auto rng = boost::adaptors::filter(vec, pred);`. It is a key to good return values though not to get too clever, consistency is the king.


[cols="1,1",options="header",stripes=even,frame=none]
|===
| *Less-Good* | *Good* 
|
`void file_size(const path& p, uintmax_t& size);   // output param for main result`
|
`bool exists(const path& p);
uintmax_t file_size(const path& p, error_code& ec);  // returns via value + error_code`
| `int parse_number(const std::string&); // -1 means failure`
| `boost::optional<int> parse_number(const std::string&);`
| `void file_size(const path& p, uintmax_t& out_size); // output param`	|  `uintmax_t file_size(const path& p);uintmax_t file_size(const path& p, error_code& ec) noexcept; // alt API`
| `std::string find_user(int id); // returns empty string if not found`	| `boost::optional<std::string> find_user(int id);`
| `int divide(int a, int b); // returns 0 if divide-by-zero`	| `boost::system::result<int> divide(int a, int b); // success or error_code`
| `int remove(std::vector<int>& v, int x); // returns count removed`	| `auto new_end = boost::remove(v, x); // returns iterator (range style)`
| `std::vector<int> filter_positive(const std::vector<int>& v); // always allocates`	| `auto rng = boost::adaptors::filter(v, [](int n){ return n > 0; }); // lazy view`
| `Config& set_option(Config& c, int x); // modifies existing config`	| `Config c = Config().set_option(42).set_flag(true); // fluent style`
|===

=== Interfaces

If a beginner can do something useful in one line of code, and an expert can still optimize/control everything with traits/policies, you've designed a good interface.

Keep interfaces minimal but composable. Boost often prefers non-member, non-friend functions to avoid bloating classes. Free functions are easier to extend later without breaking ABI.

Avoid `int` or `std::string` everywhere when domain types make intent clear. 

[cols="1,1",options="header",stripes=even,frame=none]
|===
| *Less-Good* | *Good* 
| `my_vector.reverse_in_place_with_allocator_and_logging(...);`
| `auto r = boost::adaptors::reverse(my_vector);`
| `bool schedule(const std::string& d);`
| `bool schedule(const boost::gregorian::date& d);`


|===


== See Also

* xref:best-practices.adoc[]
* xref:requirements/library-requirements.adoc[]