    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: C++ Patterns Source Cohesion and Decoupling</title>
        <link>https://members.accu.org/index.php/journals/473</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #39 - Sep 2000 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c165/">39</a>
                    (5)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c165-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c165+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;C++ Patterns Source Cohesion and Decoupling</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 September 2000 17:50:58 +01:00 or Tue, 26 September 2000 17:50:58 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a>Abstract</h2>
</div>
<p>Coupling and cohesion are non-functional properties of a
system's built structure. They have measurable effects on the ease
of comprehensibility, compilability, testing, and maintenance of
any system. In C++, decoupling begins at a physical level with code
structure. Surrounding the syntax, any system in development has a
structure of source and header files that lives in a file system.
This physical structure is often neglected to the detriment of any
system: It is sometimes impressive (and depressive) to see a clean
logical design crushed by the brute force of a poorly considered
physical structure.</p>
<p>The patterns in this paper document idiomatic practices for
organizing C++ source and header files. They are connected into a
language.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e25" id="d0e25"></a>Source
Dependency and Complexity Management</h2>
</div>
<p>Dependencies should be managed throughout the runtime,
construction time, and design time of a system. Coupling and
cohesion define, respectively, inter-connectedness and
intra-connectedness of components and their interfaces, where
component refers generally to physical elements such as files or
logical elements such as classes. It is these quantities that must
be managed if an architecture is to be stable and resilient in the
face of change: supporting natural growth and evolution, as well as
out of the box fitness for purpose and buildability.</p>
<p>On the whole a designer should strive to minimize dependencies
between elements of a system. This should not be at the cost of
making elements non-cohesive. They should be as loosely coupled as
is meaningful, and this will lead to a more supple component
structure. In turn this should lead to a more maintainable and
stable system. When something is stable it may be depended upon
without concern.</p>
<p>Practices for the physical organization of the source code
support or lead to decoupling practices that are focused on
managing class dependencies and object relationships [<a href=
"#Barton-1994">Barton-1994</a>, <a href=
"#Carroll-1995">Carroll-1995</a>, <a href=
"#Geisler1999">Geisler1999</a>, <a href=
"#Henney1999">Henney1999</a>, <a href="#Henney2000">Henney2000</a>,
<a href="#Murray1993">Murray1993</a>, <a href=
"#Riehle2000">Riehle2000</a>, <a href=
"#Sutter2000">Sutter2000</a>]. The focus in this paper is on
physical organization more than on the logical concepts represented
within a program.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e58" id="d0e58"></a>Organization of
Source Code</h3>
</div>
<p>Large-scale structure in C++ programs is dominated by use of the
preprocessor for file inclusion. However, the relationship between
physical source, such as source and header files<sup>[<a name=
"d0e63" href="#ftn.d0e63" id="d0e63">1</a>]</sup>, and logical
source, such as declarations and definitions, is not always a happy
one. The same can be said of Bjarne Stroustrup's view of this C
legacy in C++: &quot;I'd like to see Cpp abolished&quot; [<a href=
"#Stroustrup1994">Stroustrup1994</a>]. Evidently there would be
little love lost here if this were to happen.</p>
<p>The preprocessor is blunt tool for expressing module
relationships, based as it is on semantically-unconstrained textual
inclusion:</p>
<p>There is no language-recognized module structure for a system,
so physical partitioning is notionally optional and based strongly
on habit and convention - always a topic for heated debate. As
perceived by the programmer, this leads to unnecessary incidental
complexity when working with source - whether it is writing it,
compiling it, or versioning it.</p>
<p>If unmanaged, build times can rise exponentially with the number
of source and header files. In smaller projects this offers plenty
of opportunities for coffee breaks and meetings, but on larger
projects it introduces the bind of overnight builds.</p>
<p>An unwanted side effect of preprocessor usage is that legitimate
code may be terrorized and harassed by wild macros.</p>
<p>These are common forces and consequences in development.
Unmanaged physical dependencies thus make systems harder to
understand and harder to build, putting the brakes on rapid,
incremental development and turnaround. The pattern language
presented in this paper documents and links a set of practices that
balance these forces.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e86" id="d0e86"></a>The Patterns</h3>
</div>
<p>Table 1 lists the patterns described here in thumbnail form,
providing a summary of the problem and solution for each. Other key
patterns used in this paper are described toward the end in
thumbnail form in Table 2.</p>
<div class="table"><a name="d0e91" id="d0e91"></a>
<table summary=
"Thumbnails for patterns documented in this paper, listed in order."
border="1" cellspacing="0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;thead&gt;
<tr>
<th>Name</th>
<th>Problem</th>
<th>Solution</th>
</tr>
&lt;/thead&gt;
&lt;tbody&gt;
<tr>
<td>Cohesive Header</td>
<td>What partitioning criteria should be used in allocating
abstractions to header files in a system?</td>
<td>Organize a header around a single concept, such as a class or
set of services. The header should declare or include everything it
needs to be self-contained, but no more.</td>
</tr>
<tr>
<td>Source/Header Correspondence</td>
<td>What should be the relationship between header files that
declare the abstractions in a system and the source files that
define them?</td>
<td>For each header define a corresponding source file with the
definitions to the declared abstractions. The source file includes
the header and has the same base name as the header.</td>
</tr>
<tr>
<td>Idempotent Header</td>
<td>What steps should be taken to deal with header files that
include common header files, which may lead to multiple inclusion
problems?</td>
<td>A header file should have the same effect, no matter how many
times it is included. Use a Header Guard to ensure that its
contents are expanded out only the first time a header is included
in a translation unit.</td>
</tr>
<tr>
<td>Header Guard</td>
<td>What mechanism can be used to prevent multiple inclusion of a
header file leading to multiple expansion of its contents, and
hence multiple definition problems?</td>
<td>Test for the definition of a macro - based on the capitalized
version of the header's base name - only including the content of
the header if it is undefined. Define the macro only if the content
is included.</td>
</tr>
<tr>
<td>Minimal Header</td>
<td>How can a Cohesive Header include no more information than is
strictly necessary when its classes and functions mention types
defined in other header files?</td>
<td>Include only the headers that define non-class types and the
headers for classes whose definition is genuinely required, e.g.
base classes and data members by value. For each other class that
is used, e.g. as arguments or as pointers, provide a Forward
Declaration.</td>
</tr>
<tr>
<td>Forward Declaration</td>
<td>How can a class be referred to in a header without causing its
full definition to be included for compilation?</td>
<td>Declare only the class name in the header file, placing it
after any included files. In the defining source file include the
appropriate header file for all forward-declared types.</td>
</tr>
<tr>
<td>Forward Declaring Header</td>
<td>How can Forward Declarations for complex types, such as
template definitions with defaulted parameters, be declared in a
Minimal Header without hardwiring and duplicating the declaration
information over the system?</td>
<td>For such complex types, provide an additional header file that
comprises only Forward Declarations. Clients now include the
Forward Declaring Header rather than providing their own Forward
Declarations.</td>
</tr>
&lt;/tbody&gt;
</table>
<p class="title c2">Table 1. Thumbnails for patterns documented in
this paper, listed in order.</p>
</div>
<div class="figure"><a name="d0e153" id="d0e153"></a>
<div class="mediaobject c3"><img src=
"/var/uploads/journals/resources/kevlin%20henney%20source%20patterns.png" align="middle"
alt=
"Patterns and their successors for organizing C++ source and header files."></div>
<p class="title c2">Figure 1. Patterns and their successors for
organizing C++ source and header files.</p>
</div>
<p>The patterns may be organized into a pattern language, as shown
in Figure 1. <span class="emphasis"><em>Cohesive Header</em></span>
defines the natural entry point into the language, the remaining
arrows showing the subsequent flow through the language.</p>
<p>The patterns are presented using a brief, low ceremony pattern
form: pattern name followed by intent; a description of the
problem, identifying the forces; a detailed description of the
solution, identifying the consequences.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e166" id="d0e166"></a>Cohesive
Header</h2>
</div>
<p>Organize header files around a single concept to simplify their
comprehension and management.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e171" id="d0e171"></a>Problem</h3>
</div>
<p>What partitioning criteria should be used in allocating
abstractions to header files in a system?</p>
<p>It is possible for a programmer to develop a small project in a
single file. However, although this apparently simplifies tool
usage - compilation, linkage, versioning, etc. - it does not scale
well: Comprehensibility falls rapidly with size, editing becomes
increasingly awkward and Cobol-like, and opportunities for
developer teams, parallel development, separate compilation,
fine-grained versioning, reuse, unit testing, etc. are all but
eliminated. Such a seductively easy route leads quickly to a dead
end.</p>
<p>Separate source files in part resolve these issues, but
introduce the need for different source files to share common
function declarations and type definitions. The temptation is to
revert to a monolithic header file that includes all declarations
and definitions needed across a project. As with the single source
file approach, such a &quot;<tt class="filename">project.h</tt>&quot;
requires a particular presence of mind to ensure the internal
organization of the file does not degenerate into cryptic
spaghetti<sup>[<a name="d0e183" href="#ftn.d0e183" id=
"d0e183">2</a>]</sup>, a secret dish known only to those initiated
in its history and development.</p>
<p>Dividing the declarations and definitions of a project across
many header files increases the opportunity for separate
development, and many of the benefits that it brings. However,
partitioning alone is insufficient to bring in all of the benefits,
and may also be used inadvertently as a tool to reduce
comprehensib-ility: The partitioning may be coincidental or
inconsistent, making the apparent structure of the system difficult
for a programmer to navigate, modify, and extend. The resulting
header files may be large and still difficult to comprehend,
offering apparently unrelated concepts in a single place, i.e.
&quot;<tt class="filename">kitchensink.h</tt>&quot; (because they contain
&quot;everything but the kitchen sink&quot;).</p>
<p>Breaking declarations and definitions across multiple header
files will lead to implied dependencies between header files, where
one declaration depends on another. This can be awkward to manage
in source files as the programmer must be aware of and track such
subtle relationships, ensuring that they #include the right files
in the right order.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e194" id="d0e194"></a>Solution</h3>
</div>
<p>Organize a header around a single concept, such as a class or
set of services. The header should declare or include everything it
needs to be self-contained, but no more: It should also be a
<span class="emphasis"><em>Minimal Header</em></span>. A
<span class="emphasis"><em>Source/Header Correspondence</em></span>
ensures that the implementation of features offered in a
<span class="emphasis"><em>Cohesive Header</em></span> is easy to
find. An <span class="emphasis"><em>Idempotent Header</em></span>
ensures that multiple inclusion of a header is transparent in
non-hierarchical inclusion graphs (i.e. directed acyclic
graphs).</p>
<p>A <span class="emphasis"><em>Cohesive Header</em></span>
represents a physical interface that corresponds to the logical
structure. It represents a unit of common release and change. For
instance, a <span class="emphasis"><em>Cohesive Header</em></span>
may be organized around a single class and its dependent functions.
It would include any associated operators and algorithms, helper
classes, and namespace wrapping, as well as its own inclusion of
any headers whose contents it depended on. Thus to gain access to
the full use of a class a programmer need only determine which
<span class="emphasis"><em>Cohesive Header</em></span> corresponds
to that concept and include it.</p>
<p><span class="emphasis"><em>Cohesive Header</em></span> supports
and is supported by the Interface Principle [<a href=
"#Sutter2000">Sutter2000</a>], where &quot;for a class X, all functions,
including free functions, that both 'mention' X and 'are supplied
with' X are logically part of X, because they form part of the
interface of X&quot;.</p>
<p>A <span class="emphasis"><em>Cohesive Header</em></span> should
be named after its principal concept, i.e. a class or general
purpose, followed by a suffix, such as .hpp or .hh. The suffix is
generally dependent on the project and the platform culture.
Although the standard header files omit suffices, e.g. <tt class=
"filename">&lt;string&gt;</tt> and <tt class=
"filename">&lt;list&gt;</tt>, such files cannot be associated with
applications or found conveniently using wildcard matching. Many
source code editors use syntax highlighting based on identifying
the language through the suffix, and the absence of a suffix
introduces an inconvenience. The <tt class="filename">.h</tt>
suffix is generally not recommended because of its more standard
association with C header files, so that C++ headers cannot be
readily distinguished from C headers by either programmers or
tools.</p>
<p>Where namespaces are used to represent subsystems or packages,
as opposed to simply wrapping up a single class and its dependent
functions, the physical directory structure should correspond to
the logical source structure. This again makes it easier to find
and comprehend the header in question, and should also be made
apparent in the inclusion by client code, i.e. <tt class=
"literal">#include &lt;subsystem/concept.hpp&gt;</tt> rather than
simply <tt class="literal">#include &lt;concept.hpp&gt;</tt>. Such
partitioning was relatively common before the introduction of C++
namespaces, and is reinforced by their addition as well as the
adoption of the same model as the basis of Java's package
mechanism.</p>
<p>Partitioning a system's logical interfaces across <span class=
"emphasis"><em>Cohesive Header</em></span>s will result in more
header files than other partitioning criteria, which means that
there are more files for the programmer to be aware of and to
manage. However, each of these files will be smaller, more
cohesive, and - therefore - easier to comprehend and manage, e.g.
change history will clearly reflect the stability of and rate of
change of a concept. If the compiler's own file management is
limited, many small header files on a large project can have a
knock-on effect on the build time as the compiler will be
performing more file opening, reading, and closing operations.</p>
<p>As with many forms of source partitioning, <span class=
"emphasis"><em>Cohesive Header</em></span>s is a convention that
requires judgment - i.e. whether or not the contents of a given
header are genuinely cohesive. If adopted by developers, it is a
convention that is enforced beyond the control of the compiler.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e261" id="d0e261"></a>Source/Header
Correspondence</h2>
</div>
<p>Each header file should be matched by defining source file to
simplify comprehension of the system's file structure and
management of dependencies.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e266" id="d0e266"></a>Problem</h3>
</div>
<p>What should be the relationship between header files that
declare the abstractions in a system and the source files that
define them? Having partitioned the physical view of the logical
elements a system into Cohesive Headers, header file clients can
now easily locate functionality for inclusion. But what about
programmers working on the actual defining source code that
realizes the features in <span class="emphasis"><em>Cohesive
Header</em></span>? It should be simple for them to locate
definition code for reading, modification, or extension based on
the header, as well as know which header to modify if a change
requires that they be kept in synch.</p>
<p>Ada and Modula-2 have a clear correspondence between the
exported view of a package or module, but C++'s preprocessor does
not enforce any model, focusing only on the composition of a
translation unit, by inclusion and macro expansion, for further
compilation. It would be equally legitimate for a system to have
its function and data definitions grouped into a single source file
as it would be for each individual function or data item to be
assigned its own source file. The former will create a slab of code
that defies software engineering principles and the latter will
create a finely fragmented system structure that is overwhelming
for both programmers and compilers, leading to astonishingly long
build times.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e276" id="d0e276"></a>Solution</h3>
</div>
<p>For each <span class="emphasis"><em>Cohesive Header</em></span>
define a corresponding source file with the definitions to the
declared abstractions. The source file includes the header and has
the same base name as the header.</p>
<p><span class="emphasis"><em>Source/Header
Correspondence</em></span> effectively splits an abstraction into
two: Its declarative or export part, and its defining or
implementation part. This longstanding practice follows the
structure enforced by languages such as Ada and Modula-2. The two
files should have the same base name and differ only in the
appropriately corresponding suffices, i.e. <tt class=
"filename">.hpp</tt> and <tt class="filename">.cpp</tt> or
<tt class="filename">.hh</tt> and <tt class="filename">.cc</tt>.
The source file is also a unit of information hiding within which
the use of anonymous namespaces or the deprecated use of static can
keep additional implementation abstractions private. <span class=
"emphasis"><em>Source/Header Correspondence</em></span> makes the
source structure self-evident and easy to work with.</p>
<p>However, with inline functions and the include-all model for
template compilation, C++ does not follow a perfect
specification/implementation separation. <span class=
"emphasis"><em>Source/Header Correspondence</em></span> may be
further generalized to include files for inlines and headers for
templates, so that a header file provides function and data
declarations and class definitions only, and includes source for
template definitions and inline function definitions as separate
files. Such a separation of concerns simplifies source
management.</p>
<p>A source file includes its own corresponding header file, as
well as any other system and project files required for its
definitions. The recommended order for inclusion in the source file
first #include the corresponding header, next any headers developed
for the project, and finally any other system or third party
headers. Within each of these groupings any consistent ordering,
such as alphabetical, will suffice. This reinforces a <span class=
"emphasis"><em>Cohesive Header</em></span> by ensuring that headers
are genuinely self-contained, not accidentally relying on features
they do not themselves include.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e313" id="d0e313"></a>Idempotent
Header</h2>
</div>
<p>Ensure that including a header file has the same effect wherever
and whenever it is included.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e318" id="d0e318"></a>Problem</h3>
</div>
<p>What steps should be taken to deal with header files that
include common header files, which may lead to multiple inclusion
problems?</p>
<p>It is common for header files in projects to require the same
abstraction, and therefore as <span class="emphasis"><em>Cohesive
Header</em></span>s to include them. Any other source or header
file that includes these will then be including a common header
file at least twice. This can potentially cause problems: In a
single translation unit a class or function, including inline
functions, may be defined only once; multiple inclusion leads to
multiple definitions, and therefore failed compilation. For
instance:</p>
<pre class="programlisting">
// timer.hpp
#include &quot;callback.hpp&quot;
....

// viewer.hpp
#include &quot;callback.hpp&quot;
....

// main.cpp
#include &quot;timer.hpp&quot;
#include &quot;viewer.hpp&quot;
....
</pre>
<p>Such directed acyclic graphs of dependencies are inevitable in
any well-factored project, so it is often impossible as well as
impractical to mandate that repeated inclusion &quot;shall not happen&quot;.
Alternatively if header files include nothing and source files are
required to resolve all of the dependencies, the problem can be
resolved technically. However, the header files are no longer
Cohesive Headers and a source file programmer is required to know
and document explicitly not only what the header filesdependencies
of each include file are, but also the required ordering. This
makes header file usage cumbersome and unpleasant; there is more to
learn, and more to miss. In particular, the programmer must be
aware of the private section of each class and dependencies of each
inline function or template. This is acceptable for the developer
of the header file, but not for its user. It simply adds complexity
and means that can break in a build.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e332" id="d0e332"></a>Solution</h3>
</div>
<p>A header file should have the same effect, no matter how many
times it is included. Use a <span class="emphasis"><em>Header
Guard</em></span> to ensure that its contents are expanded out only
the first time a header is included in a translation unit.</p>
<p>An <span class="emphasis"><em>Idempotent Header</em></span> may
be included multiple times in producing the same translation unit
without harm. This allows <span class="emphasis"><em>Cohesive
Header</em></span> partitioning and simplifies the use of header
files from the point of view of its users, ensuring that they are
self-contained and work out of the box.</p>
<p>The portable and conventional way to implement an <span class=
"emphasis"><em>Idempotent Header</em></span> is to use a
<span class="emphasis"><em>Header Guard</em></span>, but some
compilers support a #pragma that ensures that the body of a header
is expanded out by the preprocessor only the first time it is
encountered. In principle, there are portable cases where an
<span class="emphasis"><em>Idempotent Header</em></span> need not
use a <span class="emphasis"><em>Header Guard</em></span>:
Declarations can be repeated without the ill effect caused by
repeated definitions. However, for consistency and
surprise-reduction a <span class="emphasis"><em>Header
Guard</em></span> is always recommended as the support for an
<span class="emphasis"><em>Idempotent Header</em></span>.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e368" id="d0e368"></a>Header
Guard</h2>
</div>
<p>Use conditional compilation to prevent problems arising from
multiple inclusion.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e373" id="d0e373"></a>Problem</h3>
</div>
<p>What mechanism can be used to prevent multiple inclusion of a
header file leading to multiple expansion of its contents, and
hence multiple definition problems?</p>
<p><span class="emphasis"><em>Idempotent Header</em></span>s
simplify the use of headers, but the provider of the header file
must ensure that such headers genuinely are idempotent, avoiding
the problems arising from multiple inclusion of definitions. As
this support is not automatic within the language, programmers are
required to provide it themselves, and the conventions used should
be consistent across a project.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e382" id="d0e382"></a>Solution</h3>
</div>
<p>Test for the definition of a macro - based on the capitalized
version of the header's base name - only including the content of
the header if it is undefined. Define the macro only if the content
is included. A conditional compilation guard therefore surrounds
the body of the header.</p>
<p>The basic schema for a Header Guard is</p>
<pre class="programlisting">
#ifndef HEADERBASENAME_INCLUDED
#define HEADERBASENAME_INCLUDED
.... // body of header
#endif
</pre>
<p>There are many different conventions for naming the guard macro,
and any convention adopted should meet the following criteria:</p>
<p>Macros should follow convention by being all in uppercase, i.e.
<tt class="literal">HEADERBASENAME_INCLUDED</tt> is OK, but not
<tt class="literal">HeaderBaseName_Included</tt>.</p>
<p>Leading underscores followed an uppercase letter are reserved
for use by the compiler and should be avoided, i.e. <tt class=
"literal">_HEADERBASENAME_INCLUDED</tt> should not be used. The
same is true for any use of double underscores, i.e. <tt class=
"literal">HEADERBASENAME__INCLUDED</tt> should also be avoided.</p>
<p>Any directory name required for inclusion should also be encoded
in the name to avoid clashes with other files with the same base
name, i.e. <tt class=
"literal">SUBSYSTEM_HEADERBASENAME_INCLUDED</tt>.</p>
<p>Any suffix used should consider the effect of moving header
files across platforms where the header suffix might be changed in
line with any compiler-required changes to the suffix of the source
file, i.e. <tt class="literal">HEADERBASENAME_H</tt> and <tt class=
"literal">HEADERBASENAME_HPP</tt> suggest they are tied to a
particular header suffix whereas <tt class=
"literal">HEADERBASENAME_INCLUDED</tt> and <tt class=
"literal">HEADERBASEDNAME_HEADER</tt> do not. The suffix can be
omitted altogether, but note that the macro then looks like any
other macro as opposed to a header guard, i.e. <tt class=
"literal">HEADERBASENAME</tt>.</p>
<p>The convention should be used consistently across a project.</p>
<p>This last point is important as it conforms to the principle of
least astonishment, especially when external guards are used for
larger files: Although repeated inclusion with a Header Guard does
no harm, the file is still read by the compiler, which can add
significant time for large headers and, on some systems, can
exhaust the number of file handles available to the compiler. In
such cases, a build optimization is possible by using redundant
external guards around an include [<a href=
"#Lakos1996">Lakos1996</a>]:</p>
<pre class="programlisting">
#ifndef HEADERBASENAME_INCLUDED
#include &quot;headerbasename.hpp&quot;
#endif
</pre>
<p>All header files should, regardless, define <span class=
"emphasis"><em>Header Guard</em></span>s. The programmer must
remember to do this consistently, and this can be helped by using
boilerplates or editor scripting.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e445" id="d0e445"></a>Minimal
Header</h2>
</div>
<p>A header should include no more than it needs for legal
compilation.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e450" id="d0e450"></a>Problem</h3>
</div>
<p>How can a <span class="emphasis"><em>Cohesive Header</em></span>
include no more information than is strictly necessary when its
classes and functions mention types defined in other header
files?</p>
<p>A programmer, assuming that a header is not only self-sufficient
but also sufficient, may assume that all the headers included by
the header are genuine dependencies of the header's contents.
However, it is often the case that certain headers are included by
force of habit or laziness to include certain utility files
elsewhere, e.g. <tt class="literal">#include &lt;iostream&gt;</tt>
or <tt class="literal">#include &lt;string&gt;</tt>. Such headers
are often not required by either the header or many of the source
files. This makes the dependency graph for a system confused, so
that listing <tt class="literal">#include</tt> directives does not
give an accurate reflection of the necessary and logical
dependencies in a system. It also unnecessarily increases the build
time for a given header.</p>
<p>In other cases, although all of the headers included are
<span class="emphasis"><em>Cohesive Header</em></span>s and their
concepts are used in the including header, e.g. use of a class
name, inclusion of a full header is not always necessary to allow
the code to compile. In these cases the inclusion is mostly
redundant and creates a compile-time overhead.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e474" id="d0e474"></a>Solution</h3>
</div>
<p>Include only the headers that define non-class types and the
headers for classes whose definition is genuinely required, e.g.
base classes and data members by value. For each other class that
is used, e.g. as a function argument or a pointer member, provide a
<span class="emphasis"><em>Forward Declaration</em></span>.</p>
<p>A <span class="emphasis"><em>Minimal Header</em></span> supports
<span class="emphasis"><em>Cohesive Header</em></span> principles
by ensuring that what is defined by a header is necessary and
sufficient, that it is standalone. It is the source file
programmer's responsibility to include any other header files they
see fit, but it is not the job of the header file programmer to
cater for a &quot;just in case&quot; need or to predict other possible
inclusion requirements of the header file client.</p>
<p>In projects that have come to rely on this, making the change
will involve an initial refactoring that breaks a lot of
compilation. However, the required changes will be easy to identify
and make, and following that change the system build time will be
faster and header files more self descriptive.</p>
<p>Header files with inlines and template definitions will
typically require many more inclusions because they require
implementation detail that would otherwise be in a source file. For
inline functions, it is best to be sure that they are genuinely
required and that they do have a measurable positive effect on the
runtime performance or footprint of the system, otherwise they are
simply an excuse for laziness at the expense of dependency
management and build times. For templates, techniques such as
hoisting [<a href="#Carroll-1995">Carroll-1995</a>] can be used in
reducing the inclusions required to allow compilation of a
template.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e497" id="d0e497"></a>Forward
Declaration</h2>
</div>
<p>Declare a class name rather than include its full definition in
a client header file.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e502" id="d0e502"></a>Problem</h3>
</div>
<p>How can a class be referred to in a header without causing its
full definition to be included for compilation?</p>
<p>Not all types that are included in a header are fully used in
that header, e.g. a type name may be used to declare a prototype of
as a pointer data member. For a class included for use as a base
class or whose instances are manipulated in inline or template
functions, the full definition is clearly required. For these other
cases, where only a mention of the name is required, inclusion of
the full definition seems wasteful.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e509" id="d0e509"></a>Solution</h3>
</div>
<p>It is possible to forward declare a class or struct name for use
in function prototypes, class static and extern data declarations,
pointer or reference data members, and some template parameters.
However, this does not apply to other type names, e.g. enum or
typedef names. Thus, for classes (and structs) declare only the
name in the header file, placing it after any included files. In
the defining source file include the appropriate header file for
all forward-declared types that are used. A <span class=
"emphasis"><em>Forward Declaring Header</em></span> simplifies
forward declaration for complex type names.</p>
<p>For classes defined in a namespace, the namespace can be
reopened for the forward declaration:</p>
<pre class="programlisting">
namespace subsystem
{
    class concept;
}
</pre>
<p><span class="emphasis"><em>Forward Declaring Header</em></span>s
can make this less of a chore.</p>
<p><span class="emphasis"><em>Forward Declaration</em></span>
supports <span class="emphasis"><em>Minimal Header</em></span>s
based on the principle of sufficiency, leading to improvements in
build times and reduction of recompilation when headers are
changed. The onus is now placed on the file including the header
file to include the full definition, assuming it is needed (not
always the case).</p>
<p><span class="emphasis"><em>Forward Declaration</em></span>'s
role as a dependency management idiom is the basis of the
<span class="emphasis"><em>Opaque Type</em></span> idiom, which in
turn, and along with <span class=
"emphasis"><em>Handle/Body</em></span>, forms the basis of the
<span class="emphasis"><em>Cheshire Cat</em></span> idiom. Another
technique for eliminating dependencies arising from private
implementation detail is at the logical rather than the source
level: Defining an <span class="emphasis"><em>Interface
Class</em></span> uses inheritance to eliminate any private
section, and thus any dependencies from it.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e548" id="d0e548"></a>Forward
Declaring Header</h2>
</div>
<p>Group complex forward declarations into a separate header file
to simplify client header files.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e553" id="d0e553"></a>Problem</h3>
</div>
<p>How can <span class="emphasis"><em>Forward
Declaration</em></span>s for complex types, such as template
definitions with defaulted parameters, be declared in a
<span class="emphasis"><em>Minimal Header</em></span> without
hardwiring and duplicating the declaration information over the
system?</p>
<p>For instance, if a programmer wished to declare a prototype that
took an ostream from the standard library as one of its arguments
without including any of the sizeable I/O stream headers, a
<span class="emphasis"><em>Forward Declaration</em></span> would
suggest itself as the solution:</p>
<pre class="programlisting">
namespace std
{
    class ostream;
}
</pre>
<p>However, this will not work because ostream is a typedef name
that hides a more complex type:</p>
<pre class="programlisting">
namespace std
{
    ....
    template&lt;
        typename char_type,
        typename traits = 
            char_traits&lt;char_type&gt; &gt;
      class basic_ostream;
    typedef basic_ostream&lt;char&gt; ostream;
    ....
}
</pre>
<p>Declarations of this complexity make <span class=
"emphasis"><em>Forward Declaration</em></span>s by the including
programmer impractical and error-prone, as well as susceptible to
minor changes, e.g. if a default template parameter were to
change.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e580" id="d0e580"></a>Solution</h3>
</div>
<p>For such complex types, provide an additional header file that
comprises only <span class="emphasis"><em>Forward
Declaration</em></span>s. Clients now include the <span class=
"emphasis"><em>Forward Declaring Header</em></span> rather than
providing their own <span class="emphasis"><em>Forward
Declaration</em></span>s.</p>
<p>A <span class="emphasis"><em>Forward Declaring
Header</em></span> requires the anticipation of the programmer
providing the principal header. The <span class=
"emphasis"><em>Forward Declaring Header</em></span> includes the
relevant declarations, dealing with namespace and template
parameter issues, for the user to include directly. The principal
header file can itself include the <span class=
"emphasis"><em>Forward Declaring Header</em></span>, helping to
ensure that its <span class="emphasis"><em>Forward
Declaration</em></span>s are in synch with the actual definitions,
and simplifying the management of what is now an increased number
of files.</p>
<p>The role of the header file as a <span class=
"emphasis"><em>Forward Declaring Header</em></span> should be made
clear by use of an appropriate convention, such as appending
<tt class="literal">fwd</tt> to the base name. For example,
<tt class="literal">#include &lt;iosfwd&gt;</tt>. If a consistent
and clear convention is followed, users will be more aware of these
header files, and will be more likely to use them to reduce their
dependencies and build times.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e619" id="d0e619"></a>Other
Patterns</h2>
</div>
<p>Table 2 presents other key patterns that are used in this paper.
The references given indicate where a pattern has been formally
documented as such or, alternatively, where it has been documented
as a proven, recognizable practice, possibly by a different
name.</p>
<div class="table"><a name="d0e624" id="d0e624"></a>
<table summary=
"Thumbnails for patterns used but not documented in this paper, listed alphabetically."
border="1" cellspacing="0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;thead&gt;
<tr>
<th>Name</th>
<th>Problem</th>
<th>Solution</th>
</tr>
&lt;/thead&gt;
&lt;tbody&gt;
<tr>
<td>Cheshire Cat [<a href="#Geisler1999">Geisler1999</a>, <a href=
"#Lakos1996">Lakos1996</a>, <a href="#Murray1993">Murray1993</a>,
<a href="#Sutter2000">Sutter2000</a>]</td>
<td>How can the representation of an object be fully and physically
decoupled from its usage, so that users of the object are presented
with a conventional class interface?</td>
<td>Define the representation of the object as an Opaque Type. The
Opaque Type is declared as nested and private within the class; it
is only fully defined in the same source file as the definitions of
the class's member functions.</td>
</tr>
<tr>
<td>Handle/Body [<a href="#Coplien1992">Coplien1992</a>, <a href=
"#Gamma-1995">Gamma-1995</a>]</td>
<td>How can the representation of an object be decoupled from its
usage?</td>
<td>Place the abstraction and representation into separate objects
and hierarchies, so that the abstraction is accessed via a handle
object and its representation is a separate, hidden, body
object.</td>
</tr>
<tr>
<td>Interface Class [<a href="#Barton-1994">Barton-1994</a>,
<a href="#Carroll-1995">Carroll-1995</a>, <a href=
"#Henney1999">Henney1999</a>, <a href="#Lakos1996">Lakos1996</a>,
<a href="#Riehle2000">Riehle2000</a>]</td>
<td>How can we represent the protocol for class usage without also
expressing any implementation?</td>
<td>Define a separate abstract class, containing only pure virtual
functions, to express the common capabilities of derived
classes.</td>
</tr>
<tr>
<td>Opaque Type [<a href="#Henney2000">Henney2000</a>, <a href=
"#Lakos1996">Lakos1996</a>]</td>
<td>How can the representation of an object be fully and physically
decoupled from its usage, so that a change in representation does
not require a recompilation of clients</td>
<td>In a header file, provide a Forward Declaration for the type
along with a set of functions that operate on pointers to that
type. The type is only fully defined in the same source file as the
functions that operate on it.</td>
</tr>
&lt;/tbody&gt;
</table>
<p class="title c2">Table 2. Thumbnails for patterns used but not
documented in this paper, listed alphabetically.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e704" id="d0e704"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Barton-1994" id=
"Barton-1994"></a>
<p class="bibliomixed">[Barton-1994] John J Barton and Lee R
Nackman, <span class="citetitle"><i class="citetitle">Scientific
and Engineering C++: An Introduction with Advanced Techniques and
Examples</i></span>, Addison-Wesley, 1994.</p>
</div>
<div class="bibliomixed"><a name="Carroll-1995" id=
"Carroll-1995"></a>
<p class="bibliomixed">[Carroll-1995] Martin D Carroll and Margaret
A Ellis, <span class="citetitle"><i class="citetitle">Designing and
Coding Reusable C++</i></span>, Addison-Wesley, 1995.</p>
</div>
<div class="bibliomixed"><a name="Coplien1992" id=
"Coplien1992"></a>
<p class="bibliomixed">[Coplien1992] James O Coplien, <span class=
"citetitle"><i class="citetitle">Advanced C++: Programming Styles
and Idioms</i></span>, Addison-Wesley, 1992.</p>
</div>
<div class="bibliomixed"><a name="Gamma-1995" id="Gamma-1995"></a>
<p class="bibliomixed">[Gamma-1995] Erich Gamma, Richard Helm,
Ralph Johnson, and John Vlissides, <span class=
"citetitle"><i class="citetitle">Design Patterns: Elements of
Reusable Object-Oriented Software</i></span>, Addison-Wesley,
1995.</p>
</div>
<div class="bibliomixed"><a name="Geisler1999" id=
"Geisler1999"></a>
<p class="bibliomixed">[Geisler1999] Andreas Geisler, &quot;Hidden
State&quot;, <span class="citetitle"><i class="citetitle">C++
Report</i></span> 11(10), November/December 1999.</p>
</div>
<div class="bibliomixed"><a name="Henney1999" id="Henney1999"></a>
<p class="bibliomixed">[Henney1999] Kevlin Henney, &quot;Clone Alone&quot;,
<span class="citetitle"><i class="citetitle">Overload
33</i></span>, August 1999.</p>
</div>
<div class="bibliomixed"><a name="Henney2000" id="Henney2000"></a>
<p class="bibliomixed">[Henney2000] Kevlin Henney, &quot;<span class=
"citetitle"><i class="citetitle">C++ Patterns: Principles, Idioms
and Techniques</i></span>&quot;, presented at OOP 2000 , January
2000.</p>
</div>
<div class="bibliomixed"><a name="ISO1998" id="ISO1998"></a>
<p class="bibliomixed">[ISO1998] <span class="citetitle"><i class=
"citetitle">International Standard: Programming Language -
C++</i></span>, ISO/IEC 14882:1998(E), 1998.</p>
</div>
<div class="bibliomixed"><a name="Lakos1996" id="Lakos1996"></a>
<p class="bibliomixed">[Lakos1996] John Lakos, <span class=
"citetitle"><i class="citetitle">Large-Scale C++ Software
Design</i></span>, Addison-Wesley, 1996.</p>
</div>
<div class="bibliomixed"><a name="Murray1993" id="Murray1993"></a>
<p class="bibliomixed">[Murray1993] Robert B Murray, <span class=
"citetitle"><i class="citetitle">C++ Strategies and
Tactics</i></span>, Addison-Wesley, 1993.</p>
</div>
<div class="bibliomixed"><a name="Riehle2000" id="Riehle2000"></a>
<p class="bibliomixed">[Riehle2000] Dirk Riehle, &quot;Working with
Classes and Interfaces: Five Fundamental Patterns&quot;, <span class=
"citetitle"><i class="citetitle">C++ Report</i></span> 12(3), March
2000.</p>
</div>
<div class="bibliomixed"><a name="Stroustrup1994" id=
"Stroustrup1994"></a>
<p class="bibliomixed">[Stroustrup1994] Bjarne Stroustrup,
<span class="citetitle"><i class="citetitle">The Design and
Evolution of C++</i></span>, Addison-Wesley, 1994.</p>
</div>
<div class="bibliomixed"><a name="Sutter2000" id="Sutter2000"></a>
<p class="bibliomixed">[Sutter2000] Herb Sutter, <span class=
"citetitle"><i class="citetitle">Exceptional C++</i></span>,
Addison-Wesley, 2000.</p>
</div>
</div>
</div>
<div class="footnotes"><br>
<hr class="c4" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e63" href="#d0e63" id=
"ftn.d0e63">1</a>]</sup> Unless otherwise stated, a <span class=
"emphasis"><em>source file</em></span> in this paper is considered
to be the file containing non-inline, non-template definition code,
i.e. .cpp or .cc files on many systems. These are considered
distinct from <span class="emphasis"><em>header files</em></span>
which they #include, and which #include each other, i.e. .hpp, .cc,
or .h files.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e183" href="#d0e183" id=
"ftn.d0e183">2</a>]</sup> Don't get me wrong: I love spaghetti.
It's just that it does not provide us with a useful metaphor for
good software structure; the layering of lasagna is far more suited
to this.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
