Originally posted as TotW #186 on November 5, 2020
“Everything should be made as simple as possible, but no simpler.” ~ Roger Sessions’s interpretation of Einstein
When adding a new function, default to making it a non-member function local to
.cc file where it is called. While there are valid reasons to make another
choice, consider writing it in an unnamed namespace (also known as an “anonymous
Writing a non-member in an unnamed namespace has benefits both by making
functions internal to a
.cc file (moving them out of header files) as well as
by making them non-members (moving them out of classes).
Benefits over functions declared in a header file include:
Benefits over private methods include:
Sometimes a non-member local function does not make sense. For example:
Marking a non-member function as
static has essentially the same effect as
placing it inside an unnamed namespace in terms of isolating it from code in
other translation units. While unnamed namespaces do this in a uniform manner
that covers types as well as functions and objects, some people like to see
static written explicitly in the declaration of a function to show that it is
local to a translation unit without having to check for an enclosing unnamed
namespace. While this tip recommends using an unnamed namespace, using
can be a reasonable choice.
Parts of the style guide point us in this direction, but they don’t go as far. For example:
static), but doesn’t talk about private methods.
thisis essentially an uber-input/output parameter.
File-local functions simplify dependencies and improve locality. Non-member
functions increase encapsulation, simplify class definitions, and make
dependencies more explicit. When writing a function, consider making it a
file-local non-member function, such as by putting it in an unnamed namespace of