    <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  :: From Mechanism to Method: Generic Decoupling</title>
        <link>https://members.accu.org/index.php/journals/308</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 #60 - Apr 2004 + 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/c152/">60</a>
                    (8)
<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/c152-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c152+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;From Mechanism to Method: Generic Decoupling</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 April 2004 22:54:59 +01:00 or Fri, 02 April 2004 22:54:59 +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></h2>
</div>
<p>Simplification of code is often equated with the elimination of
options. At best, this turns out to be a false correlation; at
worst, it hampers the long-term code quality and development. The
side effects of premature generalization and over-abstraction
[<a href="#Gabriel">Gabriel</a>] are as much a problem in software
as the consequences of premature optimization: complexity,
unmaintainability, brittleness, bloatware, strengthened coupling,
weakened cohesion, loss of flexibility - in short, a lot of
criticisms that we would prefer not to have leveled at our own
code.</p>
<p>It is true that in many cases of simplification options will be
eliminated, but more often than not the eliminated options are the
ones that tended to complicate the code or were of little practical
use in the first place - dead code waiting for a garbage
collector.</p>
<p>For example, in the C++ Standard library, the only noticeable
role that traits and allocator parameters of the <tt class=
"classname">std::basic_string</tt> serve is to complicate the usage
and error reporting on, typically, <tt class=
"classname">std::string</tt>. Their role is so constrained as to
make them almost completely useless. The few people that take
advantage of them are often attempting to solve the wrong problem
or are employing the wrong solution. There is in fact a great deal
of scope for increased simplicity and useful parameterization in
string types [<a href="#Alexandrescu2001">Alexandrescu2001</a>,
<a href="#Henney2001">Henney2001</a>]; it's just a shame that
<tt class="classname">std::basic_string</tt> and its moribund
parameters are already parked in that space.</p>
<p>It is possible to simplify the structure of software without
losing effective options. It is even possible to do so and increase
your options. Now, that sounds worthwhile: simpler <span class=
"emphasis"><em>and</em></span> more flexible.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e49" id="d0e49"></a>Decoupling in
General</h2>
</div>
<p>Although we cannot predict the future with any certainty, it is
still possible to write code that is graceful and accommodating -
rather than troublesome and resistant - in the face of change.
Software development is concerned with the development of structure
- partitioning and connection, separation and composition - so any
conscious and conscientious approach to software development should
have, as one of its prominent manifesto promises, a clear focus on
structure management.</p>
<p>The aggressive pursuit of LCHC (low coupling and high cohesion)
can ensure that the effect of change is simplified and isolated,
rather than traumatic and global. LCHC also simplifies testing,
building, versioning, experimentation, optimization, team
organization, and pretty much any other development activity you
can think of that absorbs more time, effort, or grief than you had
originally anticipated. Sadly, few approaches can genuinely boast
LCHC as one of their main pledges, preferring instead the active
pursuit of more obviously crowd-pleasing headlines such as
<span class="emphasis"><em>reuse</em></span>.</p>
<p>The trick to achieving generality is, somewhat
counterintuitively, to make the code specific enough to be fit for
purpose. A fit to the task in hand must be targeted with one eye;
the other should be seeking opportunities to keep options open, but
without attempting to pursue all of the choices. It is tempting to
try to enumerate all the possible ways in which something could
change and be adapted and then incorporate all the necessary hooks
and extra parameterization into your design. Unfortunately this
style tends to make your code more complex to understand. In fact,
your code can become so full of conveniences that it's almost
impossible to use either simply or correctly. Over-guessing may
narrow rather than widen your options. You - and your users - may
end up with a lot of unused code and many workarounds.</p>
<p>By contrast, a concerted focus on dependency management will
deliver you some tangible benefits in the short term - development
times, build times, lunch times - and reduce the cost of change in
the long term. The loose coupling keeps the code supple and more
stable as, over time, the genuine sources of variation, and
therefore parameterization, become apparent and needed.</p>
<p>So what are the sources of coupling in C++ code? We can classify
two basic forms of coupling:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="emphasis"><em>Physical coupling</em></span>
requires that for the compilation of one piece of code the compiler
must see another piece of code. In practical terms this means that
the code depended upon appears in the same source file or is pulled
in by <tt class="literal">#include</tt>.</p>
</li>
<li>
<p><span class="emphasis"><em>Conceptual coupling</em></span>
[<a href="#Note1">Note1</a>] implies that for a piece of code to
work there is a dependency on another concept, which may exist
either tacitly outside the code or explicitly within it. For
instance, a template parameter can be described by a set of
requirements outside the code, whereas a class definition is known
to the compiler.</p>
</li>
</ul>
</div>
<p>One does not necessarily imply the other:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>An inheritance relationship represents both a conceptual and a
physical relationship. A derived class is conceptually dependent on
its base class(es) because it may use or override features. The
compiler must also be able to see the definition of any base
classes to compile a derived class.</p>
</li>
<li>
<p>A class or function template conceptually depends on its
template parameters, but the use of the parameter does not require
any <tt class="literal">#include</tt> support. A dependency on an
actual parameter type occurs at the point of use of instantiation,
but not at the point of definition.</p>
</li>
<li>
<p>The use of inline functions or template code written in headers
may introduce a physical dependency, but not necessarily a
conceptual dependency. Use of an inline function or a class
template also pulls in any of the dependencies that are used in
implementation, but are not relevant to the usage interface.</p>
</li>
</ul>
</div>
<p>There are four complementary approaches for decoupling a C++
system.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e99" id="d0e99"></a>Dynamic
Typing</h2>
</div>
<p>Why does that compile-link cycle take so long? Static type
checking is the root cause of the delay; the design of the
preprocessor merely exacerbates the issue. Want to know that your
code makes at least basic sense? Let the compiler check your types
and how you're using them and then let the linker tie all the loose
ends in your program together. Efficiency and confidence in
execution is your reward; extended surfing breaks and water cooler
conversations are your punishment. Hmm, OK, perhaps we need a
different spin on this: long build times put the <span class=
"emphasis"><em>irritation</em></span> and <span class=
"emphasis"><em>detrimental</em></span> into iterative and
incremental development, frustration and time wasting that are only
temporarily relieved by a machine upgrade.</p>
<p>If you weaken the type system you reduce the physical
dependencies. This may conjure up images of <span class="type">void
*</span> in your mind, but banish those thoughts immediately: I
want to loosen coupling, but the kind of unsafe promiscuity that
<span class="type">void *</span> often encourages is not quite what
I had in mind. A more dynamically checked type system lies at the
heart of many interpreted languages, from LISP to Smalltalk, Awk to
Ruby. Good support for reflection allows you to get at the soft
underbelly of other statically typed systems, such as Java or the
meta-information available in many component middleware
architectures. It is a matter of balance: you loosen the checking
at compile time to increase flexibility, but you increase scope for
failure at run time. You pays your money; you makes your choices;
you takes your chances. That's the essence of design.</p>
<p>C++ does not currently have good standard support for
reflection: the existing RTTI mechanism is a foot in the door, but
no more. In spite of the half-open door, C++ programs often make
effective use of dynamic typing:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Variant types, such as <tt class="classname">boost::any</tt>
[<a href="#Henney2000">Henney2000</a>, <a href="#Boost">Boost</a>]
or CORBA's any type, can hold values of arbitrary type. Depending
on your application you can choose to leave the type fully
uninterpreted, as in the case of any, or you can impose constraints
on the contained types that are reflected in the interface of the
variant (e.g., comparison or arithmetic operations).</p>
</li>
<li>
<p>Work in terms of strings, interpreting them as necessary and
with respect to the context. In the Age of the Internet, strings
are the new integers: everyone's using them for everything. Whether
we are talking about internal command languages or data exchange,
strings are remarkably versatile - given the right functions and
classes, they support the Three Rs. You can take some of the
guesswork out of how to structure your data and work with it by
adopting a data definition language or meta-language, of which XML
is certainly the most fashionable.</p>
</li>
</ul>
</div>
<p>However, remember that these techniques reduce only the physical
dependencies not the conceptual ones. Those are as strong as ever
and will be lining up to bite you at run time should you disrespect
them. You still need to know how to use them. Their correct usage
is now implicit rather than explicit, and semantic drift between
versions or developers is all too easy.</p>
<p>Flexibility has a price... and a number. This was recently
brought home to me when I was entering a particularly long order
number into a spreadsheet cell: the spreadsheet abbreviated the
many significant digits of the reference number using scientific
notation. Aha, yes, it <span class="emphasis"><em>is</em></span> a
number, just not <span class="emphasis"><em>that</em></span> kind
of number.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e146" id="d0e146"></a>Interface
Classes</h2>
</div>
<p>Inheritance in its most common employment seems to be used more
for subclassing (with a focus on inheritance of code) than for
subtyping (with a focus on classification and substitutability).
Hierarchies that accumulate implementation, often with concrete
classes inheriting from concrete classes, lead to classes that are
hard to understand.</p>
<p>But <span class="emphasis"><em>common</em></span> is not the
same as <span class="emphasis"><em>recommended</em></span>: such
usage is in direct contrast to much of the advice on practice that
is available and held in some regard. For instance, only the leaves
of a hierarchy should be concrete; its roots should be fully
abstract. virtual functions should be introduced into a hierarchy
as pure virtuals rather than with default implementations that must
be guessed, and delegation and non-public derivation should be used
to acquire implementation when there is no intent to hold a
reference or pointer to a base class.</p>
<p>Is this just so much theory? No, it's better than either just
theory or just practice: it's both. In practice it can be
demonstrated that the failure to use inheritance in a controlled
manner can be much worse than not using it at all [<a href=
"#Hatton">Hatton</a>]. The use of deep hierarchies, with
implementation scattered, defaulted, accumulated, and overridden
over a derived trail of concrete classes, actively ambushes our
ability as humans to grasp all the features of a concept within a
single embrace. This kind of inheritance often sabotages the
localization benefits of encapsulation.</p>
<p>All this may sound harsh and idealistic, but it is typically
less harsh and far less idealistic than believing in the timely
development, and appropriate quality, of a project that takes the
common but unrecommended path. Of course there is wriggle room for
pragmatism, for compromise. But remember that <span class=
"emphasis"><em>to compromise</em></span> has two different meanings
- make sure you choose the one that means to s<span class=
"emphasis"><em>ettle or resolve by making concessions</em></span>
rather than the one that means <span class="emphasis"><em>to expose
to suspicion, disrepute, or mischief</em></span>.</p>
<p>Inheritance is the strongest form of logical coupling you can
have. The need for physical coupling follows in its wake: base
classes must be directly visible or included in the source above
their derived classes. But derivation is a blade with two edges:
you can also use it to reduce coupling in a system.</p>
<p>An <span class="emphasis"><em>interface class</em></span>
[<a href="#Carroll-">Carroll-</a>, <a href=
"#Henney2001_2">Henney2001_2</a>] (also known as a <span class=
"emphasis"><em>protocol class</em></span> [<a href=
"#Lakos">Lakos</a>]) refocuses a class hierarchy's clients on the
conceptual interface, away from the physical baggage and
variability of its descendents. The absence of code in an interface
class contributes to its stability [<a href="#Martin">Martin</a>]
and comprehensibility - although a code-free class sometimes
clashes with a programmer's instincts for producing executable
code. The Observer pattern [<a href="#Gamma-">Gamma-</a>] is an
example of a larger pattern that includes this smaller
interface-decoupling pattern:</p>
<pre class="programlisting">
class subject;

class observer 
{
public:
  virtual ~observer();
  virtual void update(subject *) = 0;
protected:
  observer() {}
private:
  observer(const observer &amp;);
  observer &amp;operator=(const observer &amp;);
};
</pre>
<p>The use of virtual functions in interface classes is distinctly
public. Such a recommendation is clearly in tension with the
alternative recommendation that class hierarchies should always
have non-virtual public interfaces [<a href=
"#Sutter2001">Sutter2001</a>]. A number of practices, such as the
Template Method pattern [<a href="#Gamma-">Gamma-</a>] and the
corresponding Form Template Method refactoring [<a href=
"#Fowler">Fowler</a>], tend to give rise to nonvirtual public
interfaces in C++. Such interfaces have some useful properties, but
they typically arise as a consequence of specific practices rather
than being a necessary and general virtue in their own right. They
are by no means the only tool in the box. Design should be
considered a dialogue with a situation rather than a monologue;
there is often more than one reasonable route that such a
conversation may take.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e213" id="d0e213"></a>Hidden
Delegation</h2>
</div>
<p>Wherever there is a recommendation concerning inheritance, you
can be sure that not far behind it is a contrasting recommendation
framed in terms of delegation. The root of delegation-based
decoupling is the forward declaration. It can be used both to
resolve the problem of tail-chasing cyclic dependencies and to
reduce the exposed physical dependency of using an <tt class=
"literal">#include</tt>, reducing the essential surface area
between class definitions:</p>
<pre class="programlisting">
class observer;

class subject 
{
public:
  virtual ~subject();
  virtual void attach(observer *) = 0;
  virtual void detach(observer *) = 0;
  ...
protected:
  subject() {}
private:
  subject(const subject &amp;);
  subject &amp;operator=(const subject &amp;);
};
</pre>
<p>For classes that are, by nature, concrete and not part of a
class hierarchy, interface decoupling through interface classes has
relatively little to offer. Value objects [<a href=
"#Henney2000">Henney2000</a>], for instance, are best manipulated
directly in terms of their concrete type. Interface classes are
primarily a means for decoupling class hierarchies. Another
practice is required for specifically concrete classes.</p>
<p>The common idiom goes by various names, of which the most
evocative is also the name originally coined for it in the late
1980s: the Cheshire Cat idiom [<a href="#Murray">Murray</a>]. The
name, taken from Lewis Carroll's surreal cat whose ability to
disappear except for its grin quite bemused Alice, is apt:</p>
<pre class="programlisting">
class cat 
{
public:
  ...
private:
  class body;
  body *self;
};
</pre>
<p>Here the representation disappears entirely from the class
definition in the header, leaving behind only the discreet smile of
a pointer. The details of the body are elaborated in the
corresponding source file:</p>
<pre class="programlisting">
class cat::body 
{
public:
  body();
  ~body();
  ... // representation details
};
</pre>
<p>This technique also goes by the name of the Pimpl idiom
[<a href="#Sutter2000">Sutter2000</a>] or, very descriptively, as
the Fully Insulating Concrete Class [<a href="#Lakos">Lakos</a>].
Naturally, all idioms have consequences that must be considered:
the additional level of indirection, extra memory management, and
restriction on inlined functions are the price of the afforded
creature comforts in this case. The introduction of this separation
also allows representation sharing, although this is not a path one
should tread either necessarily or lightly [<a href=
"#Henney2001">Henney2001</a>].</p>
<p>Cheshire Cats can be introduced to complement the use of
interface classes, ensuring that class hierarchy users are as
insulated from representation details as possible. However, they
are less effective with class templates. Compiler portability
constraints mean that it is common to require the definition of
class template members in header files. In such situations, having
to include the full definition of the nested body in the header
rather takes the smile off the technique.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e252" id="d0e252"></a>Template
Parameters</h2>
</div>
<p>Templates are not normally associated with loosening physical
coupling. Quite the opposite. The inclusion of source code in
headers imposes a significant burden on the size of headers and the
patience of the programmer. However, the conceptual loosening that
arises from defining function and class templates independently of
their actual template parameter types has a knock-on physical
decoupling effect. The point at which the physical dependency on
the actual parameter type is needed is deferred to the point of use
in the code.</p>
<p>Generic decoupling forms the basis of generic programming and
the STL: templated iterator ranges for algorithm-based functions
and container constructors, and templated value types to allow any
appropriate convertible value to be used in a function, member or
non-member. The following function (inlined for brevity) shows how
the implementation of an Observer's subject class might use
existing STL features to automate observer updates:</p>
<pre class="programlisting">
class subjected : public subject 
{
  ...
  void notify() 
  {
    std::for_each(observers.begin(), observers.end(),
                  std::bind2nd(
                    std::mem_fun(&amp;observer::update),this));
  }
  ...
  std::list&lt;observer *&gt; observers;
};
</pre>
<p>An alternative approach perhaps demonstrates a number of
generic-decoupling techniques a little more explicitly:</p>
<pre class="programlisting">
template&lt;typename argument_type&gt;
class update 
{
public:
  explicit update(argument_type argument)
     : argument(argument) 
  {}

  template&lt;typename updateable&gt;
  void operator()(updateable *target) const 
  {
    target-&gt;update(argument);
  }
private:
  argument_type argument;
};

template&lt;typename argument_type&gt;
update&lt;argument_type&gt;
updater(argument_type argument) 
{
  return update&lt;argument_type&gt;(argument);
}
</pre>
<p>This generalized code leads to the following crisp usage:</p>
<pre class="programlisting">
class subjected : public subject {
  ...
  void notify() 
  {
    std::for_each(observers.begin(), observers.end(), updater(this));
  }
  ...
  std::list&lt;observer *&gt; observers;
};
</pre>
<p>The obvious trade off with using templates to decouple is that
implementation detail typically migrates to header files. This is
particularly noticeable when introducing member function templates
in place of ordinary member functions. Another consequence of the
decision to template member functions is that they cannot be
declared virtual. A more dynamically typed, variant-based approach
can counterbalance this [<a href="#Henney2000">Henney2000</a>,
<a href="#Henney2000_2">Henney2000_2</a>].</p>
<p>What is also apparent with generic decoupling is that the code
tends to become more flexible and more precise as an immediate
consequence. For instance, a different take on the needs of an
observer dispenses with the need for any forward declarations:</p>
<pre class="programlisting">
template&lt;typename subject&gt;
class observer 
{
public:
  virtual ~observer();
  virtual void update(subject *) = 0;
protected:
  observer() {}
private:
  observer(const observer &amp;);
  observer &amp;operator=(const observer &amp;);
};
</pre>
<p>And consequently allows more flexible and varied observing:</p>
<pre class="programlisting">
class data;
class events;
class watcher : public observer&lt;data&gt;, public observer&lt;events&gt; 
{
public:
  virtual void update(data *);
  virtual void update(events *);
  ...
};
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e285" id="d0e285"></a>Noosely
Coupled Exceptions</h2>
</div>
<p>As another worked example of generic decoupling, it is possible
to loosen the noose of cyclic dependencies. Consider the standard
exception classes defined in <tt class=
"filename">&lt;stdexcept&gt;</tt>. Each exception takes a
<tt class="classname">std::string</tt> for construction. Note that
<tt class="classname">std::string</tt> is mentioned only in the
single argument constructor: There is no requirement that it is
used for implementation, and the only query function offered by the
standard exceptions, <tt class="filename">&lt;stdexcept&gt;</tt>,
returns a <span class="type">const char *</span>. Given this
asymmetry in construction versus query types, and the role of
exceptions in a program, it is certainly open to question whether
std::string should be used at all in the interface.</p>
<p>However, the issue is not so much with the choice of type
dependencies in the library in general, but with the nature of the
dependencies: The <tt class="filename">&lt;string&gt;</tt> header
defines <tt class="classname">std::basic_string</tt>, some of whose
functions throw <tt class="exceptionname">std::out_of_range</tt>.
There is therefore a cyclic dependency between the types defined in
<tt class="filename">&lt;stdexcept&gt;</tt> and those in <tt class=
"filename">&lt;string&gt;</tt>; this logical dependency is made
more physical when inlined implementations are used - the norm for
template implementations. The absence of a standard
&lt;stringfwd&gt; header or a more general concept of strings means
that each vendor is invited to break the cycle in their own way,
some of which meet users expectations and some of which do not
(e.g., <span class="type">char *</span> may or may not convert
implicitly for the exception constructor argument).</p>
<p>As an aside, it can be considered surprising that exceptions are
granted the privilege to use string given that I/O and file
handling, which are more obviously and intimately connected with
string handling, have no such honor. Although file streams depend
on <tt class="classname">char_traits</tt>, as found in <tt class=
"filename">&lt;string&gt;</tt>, <span class="type">const char
*</span> is used as the type for naming files and the type for
predefined string insertion and extraction. The <tt class=
"filename">&lt;string&gt;</tt> header itself depends on I/O
streams, representing another dependency noose.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e339" id="d0e339"></a>Loosening the
Noose</h2>
</div>
<p>Returning to the <tt class="filename">&lt;stdexcept&gt;</tt> and
<tt class="filename">&lt;string&gt;</tt> cycle, a decoupling can be
arrived at by considering sufficiency and substitutability: the
exception classes in <tt class="filename">&lt;stdexcept&gt;</tt>
are conceptually more primitive than <tt class=
"classname">std::string</tt> and should not have the imposition and
dependency on such a specific string type. The dependency should be
narrower and more accommodating. The diversity of string-user needs
means that such users cannot be characterized collectively as a
community. Likewise, their needs cannot be met by a single type
such as <tt class="classname">std::basic_string</tt> - a class
template that attempts to be all things to all people, but manages
only a few in each case.</p>
<p>So what if we don't depend on a specific string type at all? The
following is an alternative version of <tt class=
"exceptionname">std::logic_error</tt>, which uses a dynamically
allocated <span class="type">char *</span> internal representation
and has no dependency on <tt class=
"filename">&lt;string&gt;</tt>:</p>
<pre class="programlisting">
class logic_error : public exception 
{
public:
  explicit logic_error(const char *detail)
     : detail(duplicate(detail, strchr(detail, '\0'))) 
  {}

  template&lt;typename string&gt;
  explicit logic_error(const string &amp;detail)
    : detail(duplicate(detail.begin(), detail.end())) 
  {}

  logic_error(const logic_error &amp;other)
    : detail(duplicate(other.detail, strchr(other.detail, '\0'))) 
  {}

  logic_error &amp;operator=(const logic_error &amp;rhs) 
  {
    char *new_detail = duplicate(rhs.detail, strchr(rhs.detail, '\0'));
    delete[] detail;
    detail = new_detail;
    return *this;
  }

  virtual ~logic_error() 
  {
    delete[] detail;
  }

  virtual const char *what() const throw() 
  {
    return detail;
  }

private:
  template&lt;typename iterator&gt;
  static char *duplicate(iterator begin, iterator end) 
  {
    char *result = new char[end - begin + 1];
    copy(begin, end, result);
    result[end - begin] = '\0';
    return result;
  }
  char *detail;
};
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e372" id="d0e372"></a>Lightly
Strung</h2>
</div>
<p>The most commonly used string initializer for exceptions is a
vanilla null-terminated character sequence. In the revised
<tt class="exceptionname">logic_error</tt> shown, this maps
directly to a constructor without requiring conversions and the
creation of temporary string objects:</p>
<pre class="programlisting">
throw std::logic_error(&quot;illogical&quot;);
</pre>
<p>The templated constructor caters to the standard string type,
and indeed any other character container that satisfies the minimal
requirements for begin and end members that return randomaccess
iterators - SGI's rope [<a href="#STL">STL</a>], <tt class=
"classname">std::vector&lt;char&gt;</tt>, or a suitable string type
of your own devising. So with a few obvious drawbacks, not only has
the cyclic dependency been removed, the generality of the code has
been increased:</p>
<pre class="programlisting">
std::vector&lt;char&gt; message;
...
throw std::logic_error(message);
</pre>
<p>I said <span class="emphasis"><em>few</em></span> drawbacks.
That is not to say that there are none. However, the most obvious
and significant limitation may not be considered that great a
disadvantage: a string type that has a userdefined conversion to
<span class="type">char *</span>, but does not sport <tt class=
"function">begin</tt> and <tt class="function">end</tt> functions,
can no longer be used to directly initialize a <tt class=
"exceptionname">logic_error</tt>. The success of such a conversion
is not guaranteed in the existing Standard, but the arrangement of
types in the headers often supports it. The suggested redesign is
forward rather than backward looking: string classes that support
such user-defined conversions are unsafe and the absence of support
for container operations is nonstandard. So if you were to rework
your own existing classes to support this style of string
decoupling, existing code that worked in terms of legacy string
classes would need to be modified - either with explicit casts or,
taking the hint, with more standard-conforming types.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e409" id=
"d0e409"></a>Conclusion</h2>
</div>
<p>Code should be supple, not subtle. For code there is such a
thing as being too well connected and too eager to please.
Generality and reuse are often better served by paying attention to
necessity and to the core activities of software development -
comprehension, change, and confirmation - than to whimsy and
speculation.</p>
<p>Refactoring code to reduce its coupling often has the effect of
increasing its cohesion. In the exception example, physical and
conceptual decoupling improved the precision of the requirement on
the string type: only specific features were required, not the
whole interface. This LCHC strategy suggests a design path that is
as applicable to domain-specific libraries as it is to the
liberalization of string types.</p>
<div class="sidebar">
<p>This article was originally published on the C/C++ Users Journal
C++ Experts Forum in November 2001 at <a href=
"http://www.cuj.com/experts/documents/s=7989/cujcexp1911Henney/"
target=
"_top">http://www.cuj.com/experts/documents/s=7989/cujcexp1911Henney/</a></p>
<p>Thanks to Kevlin for allowing us to reprint it.</p>
</div>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e423" id="d0e423"></a>References and
Notes</h2>
</div>
<div class="bibliomixed"><a name="Gabriel" id="Gabriel"></a>
<p class="bibliomixed">[Gabriel] Richard P. Gabriel. <span class=
"citetitle"><i class="citetitle">Patterns of Software: Tales from
the Software Community</i></span> (Oxford, 1996).</p>
</div>
<div class="bibliomixed"><a name="Alexandrescu2001" id=
"Alexandrescu2001"></a>
<p class="bibliomixed">[Alexandrescu2001] Andrei Alexandrescu.
&quot;Generic&lt;Programming&gt;: A Policy- Based basic_string
Implementation,&quot; <span class="citetitle"><i class="citetitle">C/C++
Users Journal C++ Experts Forum</i></span>, June 2001, <span class=
"bibliomisc"><a href="http://www.cuj.com/experts/1906/alexandr.htm"
target="_top">www.cuj.com/experts/1906/alexandr.htm</a></span></p>
</div>
<div class="bibliomixed"><a name="Henney2001" id="Henney2001"></a>
<p class="bibliomixed">[Henney2001] Kevlin Henney. &quot;From Mechanism
to Method: Distinctly Qualified,&quot; <span class="citetitle"><i class=
"citetitle">C/C++ Users Journal C++ Experts Forum</i></span>, May
2001, <span class="bibliomisc"><a href=
"http://www.cuj.com/experts/1905/henney.htm" target=
"_top">www.cuj.com/experts/1905/henney.htm</a></span></p>
</div>
<div class="bibliomixed"><a name="Note1" id="Note1"></a>
<p class="bibliomixed">[Note1] <span class="bibliomisc">Conceptual
dependencies are sometimes referred to as logical dependencies. The
distinction between - and separation of - <span class=
"emphasis"><em>logical</em></span> from <span class=
"emphasis"><em>physical</em></span> has been handed down to us from
structured analysis and design. However, the bias inherent in the
use of the word logical tends to cast all physical concerns into
the shade as impure and irrational. Such Puritanism is of little
practical use. The natural complement of p<span class=
"emphasis"><em>hysical is conceptual</em></span> rather than
<span class="emphasis"><em>logical</em></span>, whose antonym is
<span class="emphasis"><em>illogical</em></span>. C++'s reliance on
the preprocessor may not be elegant, but, given its rules, it is
entirely logical that a piece of code requiring a declaration in a
header file should also have a physical dependency on
it.</span></p>
</div>
<div class="bibliomixed"><a name="Henney2000" id="Henney2000"></a>
<p class="bibliomixed">[Henney2000] <span class="bibliomisc">Kevlin
Henney. &quot;From Mechanism to Method: Valued Conversions,&quot;
<span class="citetitle"><i class="citetitle">C++ Report</i></span>,
July-August 2000, <a href="http://www.curbralan.com" target=
"_top">www.curbralan.com</a></span></p>
</div>
<div class="bibliomixed"><a name="Boost" id="Boost"></a>
<p class="bibliomixed">[Boost] <span class="bibliomisc">Boost C++
Libraries, www.boost.org</span></p>
</div>
<div class="bibliomixed"><a name="Hatton" id="Hatton"></a>
<p class="bibliomixed">[Hatton] <span class="bibliomisc">Les
Hatton. &quot;Does OO Sync with the Way We Think?&quot;, <span class=
"citetitle"><i class="citetitle">IEEE Software</i></span>, 1998,
<a href="http://www.oakcomp.co.uk" target=
"_top">www.oakcomp.co.uk</a></span></p>
</div>
<div class="bibliomixed"><a name="Carroll-" id="Carroll-"></a>
<p class="bibliomixed">[Carroll-] <span class="bibliomisc">Martin
D. Carroll and Margaret A. Ellis. <span class="citetitle"><i class=
"citetitle">Designing and Coding Reusable C++</i></span>
(Addison-Wesley, 1995).</span></p>
</div>
<div class="bibliomixed"><a name="Henney2001_2" id=
"Henney2001_2"></a>
<p class="bibliomixed">[Henney2001_2] <span class=
"bibliomisc">Kevlin Henney. &quot;From Mechanism to Method: Total
Ellipse,&quot; <span class="citetitle"><i class="citetitle">C/C++ Users
Journal C++ Experts Forum</i></span>, March 2001, <a href=
"http://www.cuj.com/experts/1903/henney.htm" target=
"_top">www.cuj.com/experts/1903/henney.htm</a></span></p>
</div>
<div class="bibliomixed"><a name="Lakos" id="Lakos"></a>
<p class="bibliomixed">[Lakos] <span class="bibliomisc">John Lakos.
<span class="citetitle"><i class="citetitle">Large-Scale C++
Software Design</i></span> (Addison- Wesley, 1996).</span></p>
</div>
<div class="bibliomixed"><a name="Martin" id="Martin"></a>
<p class="bibliomixed">[Martin] <span class="bibliomisc">Robert C.
Martin. &quot;Object-Oriented Design Quality Metrics: An Analysis of
Dependencies,&quot; <span class="citetitle"><i class=
"citetitle">ROAD</i></span>, September-October 1995, <a href=
"http://www.objectmentor.com" target=
"_top">www.objectmentor.com</a></span></p>
</div>
<div class="bibliomixed"><a name="Gamma-" id="Gamma-"></a>
<p class="bibliomixed">[Gamma-] <span class="bibliomisc">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).</span></p>
</div>
<div class="bibliomixed"><a name="Sutter2001" id="Sutter2001"></a>
<p class="bibliomixed">[Sutter2001] <span class="bibliomisc">Herb
Sutter. &quot;Sutter's Mill: Virtuality,&quot; <span class=
"citetitle"><i class="citetitle">C/C++ Users Journal</i></span>,
September 2001.</span></p>
</div>
<div class="bibliomixed"><a name="Fowler" id="Fowler"></a>
<p class="bibliomixed">[Fowler] <span class="bibliomisc">Martin
Fowler. <span class="citetitle"><i class="citetitle">Refactoring:
Improving the Design of Existing Code</i></span> (Addison-Wesley,
1999).</span></p>
</div>
<div class="bibliomixed"><a name="Murray" id="Murray"></a>
<p class="bibliomixed">[Murray] <span class="bibliomisc">Robert B.
Murray. <span class="citetitle"><i class="citetitle">C++ Strategies
and Tactics</i></span> (Addison- Wesley, 1993).</span></p>
</div>
<div class="bibliomixed"><a name="Sutter2000" id="Sutter2000"></a>
<p class="bibliomixed">[Sutter2000] <span class="bibliomisc">Herb
Sutter. <span class="citetitle"><i class="citetitle">Exceptional
C++</i></span> (Addison-Wesley, 2000).</span></p>
</div>
<div class="bibliomixed"><a name="Henney2000_2" id=
"Henney2000_2"></a>
<p class="bibliomixed">[Henney2000_2] <span class=
"bibliomisc">Kevlin Henney. &quot;From Mechanism to Method: Function
Follows Form,&quot; <span class="citetitle"><i class="citetitle">C/C++
Users Journal C++ Experts Forum</i></span>, November 2000, <a href=
"http://www.cuj.com/experts/1811/henney.htm" target=
"_top">www.cuj.com/experts/1811/henney.htm</a></span></p>
</div>
<div class="bibliomixed"><a name="STL" id="STL"></a>
<p class="bibliomixed">[STL] <span class="bibliomisc">SGI Standard
Template Library Programmer's Guide, <a href=
"http://www.sgi.com/tech/stl/" target=
"_top">www.sgi.com/tech/stl/</a></span></p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
