    <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: The Safe Stacking of Cats</title>
        <link>https://members.accu.org/index.php/articles/235</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>




<div class="xar-mod-head"><span class="xar-mod-title">Design of applications and programs + Overload Journal #62 - Aug 2004</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/articles/">All</a>

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

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c67/">Design</a>
<br />

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c150/">62</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c67-150/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c67+150/">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: The Safe Stacking of Cats</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 01 August 2004 22:52:10 +01:00 or Sun, 01 August 2004 22:52:10 +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>In spite of some obvious differences - and the similarity that
neither can be considered a normal practice - curling and throwing
have something in common: curling is a bizarre sport played on ice;
throwing in C++ is often played on thin ice. It is the thin ice
that has most often caused consternation, and the balanced art of
not falling through that has attracted much attention.</p>
<p>By coincidence, curling is also something in which cats both
indulge and excel, putting the <span class=
"emphasis"><em>pro</em></span> into <span class=
"emphasis"><em>procrastination</em></span>. But more on cats
later.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e30" id="d0e30"></a>Taking
Exception</h2>
</div>
<p>Exceptions are disruptive but modular. The common appeal to
consider them as related to the <tt class="literal">goto</tt> is
more than a little misleading (&quot;considering <tt class=
"literal">goto</tt>&quot; considered harmful, if you like). That they
are both discontinuous is one of the few features they share. It is
an observation that although true is not necessarily useful:
<tt class="literal">break</tt>, <tt class="literal">continue</tt>,
and <tt class="literal">return</tt> also share this description of
behavior. A quick dissection exposes the differences:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="bold"><b>Transferred information:</b></span></p>
<p>a <tt class="literal">goto</tt> can associate only with a label
whereas a <tt class="literal">throw</tt> communicates with respect
to both type and any information contained in the type instance. In
this sense, the <tt class="literal">throw</tt> acts more like a
<tt class="literal">return</tt>, communicating an exceptional
rather than a normal result.</p>
</li>
<li>
<p><span class="bold"><b>Locality:</b></span></p>
<p>a <tt class="literal">goto</tt> has meaning only within a
function, labels being the only C++ entity with function scope. By
contrast, exception handling is primarily about transferring
control out of a function. It shares this with <tt class=
"literal">return</tt>, but potentially has the whole of the call
stack rather than just the immediate caller within its reach. It
also shares with <tt class="literal">break</tt> and <tt class=
"literal">continue</tt> a relationship with an enclosing control
flow primitive, so exception handling can also be used simply at
the block level.</p>
</li>
<li>
<p><span class="bold"><b>Destination coupling:</b></span></p>
<p>the target of a <tt class="literal">goto</tt> is fixed,
hardwired at compile time. There is no way to express &quot;the
following has happened, so whoever can sort it out, please sort it
out.&quot; Exceptions are independent of lexical scope and do not
nominate their handlers explicitly. Instead, nomination is dynamic
and by requirement - &quot;the first one that can handle one of these
gets to sort it out.&quot; Exceptions can be handled or ignored at
different call levels without intervention from any of the levels
in between. In many ways, the <tt class=
"literal">try</tt>/<tt class="literal">catch</tt> mechanism
resembles an advanced selection control structure - an <tt class=
"literal">if</tt>/<tt class="literal">else</tt> with extreme
attitude.</p>
</li>
<li>
<p><span class="bold"><b>Block structure:</b></span></p>
<p>Taligent's Guide to Designing Programs pulls no punches in
stating that &quot;<span class="quote">a <tt class="literal">goto</tt>
completely invalidates the high-level structure of the code</span>&quot;
[<a href="#Taligent">Taligent</a>]. Far from being merely a
provocative statement, this is a concise summary of fact. C++ is
essentially block structured: exceptions respect and work within
this structure, whereas gotos largely ignore and disrespect it.</p>
</li>
</ul>
</div>
<p>The differences are thrown (sic) into sharp relief when you
attempt to refactor code. Say that you wish to factor a block out
as a function (the Extract Method refactoring [<a href=
"#Fowler">Fowler</a>]); it is trivial to factor out the data flow:
looking at the data that's used and affected in the block tells you
what arguments and results you need to pass and how. With control
flow, unless you flow off the bottom of a block or <tt class=
"literal">throw</tt>, you cannot factor the code simply.
Traditional discontinuous control flow is nonmodular and requires
additional restructuring to communicate to the caller that a
<tt class="literal">break</tt>, <tt class="literal">return</tt>,
<tt class="literal">continue</tt>, or <tt class="literal">goto</tt>
(especially) must be effected. This is not the case with <tt class=
"literal">throw</tt>: both the overall structure and the
fine-grained detail remain unchanged.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e146" id="d0e146"></a>State
Corruption</h3>
</div>
<p>This all sounds straightforward - or straight backward if you
take the call stack's perspective - because we know about
modularity, both structured programming and object-oriented
programming are built on that foundation. However, there is still
that one small matter of &quot;disruption.&quot; When an exception is thrown,
the only thing you want disrupted is the control flow, not the
integrity of the program.</p>
<p>Any block of code may be characterized with respect to the
program's stability in the event of an exception. We can guarantee
different levels of safety, of which three are commonly recognized
[<a href="#Sutter2000">Sutter2000</a>], plus the (literally)
degenerate case:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="bold"><b>No guarantee of exception
safety:</b></span></p>
<p>ensures disruption, corruption, and chaos. Code written without
exceptions in mind often falls into this category, leaking memory
or leaving dangling pointers in the event of a thrown exception -
converting the exceptional into the unacceptable. In short, all
bets are off.</p>
</li>
<li>
<p><span class="bold"><b>Basic guarantee of exception
safety:</b></span></p>
<p>ensures that the thrower will not leak or corrupt resources.
Objects involved in the execution will be in a stable and usable,
albeit not necessarily predictable, state.</p>
</li>
<li>
<p><span class="bold"><b>Strong guarantee of exception
safety:</b></span></p>
<p>ensures that a program's state remains unchanged in the presence
of exceptions. In other words, commit-rollback semantics.</p>
</li>
<li>
<p><span class="bold"><b>No-throw guarantee of exception
safety:</b></span></p>
<p>ensures that exceptions are never thrown, hence the question of
how program state is affected in the presence of an exception need
never be answered because it is purely hypothetical.</p>
</li>
</ul>
</div>
<p>The stroke of midnight separates the first, degenerate category
of exception unsafety from the last, Zen-like guarantee of benign
order through the simple absence of disruption. Code written to
achieve these guarantees may have the same structure, but will
differ in the not-so-small detail of whether or not exceptions
occur anywhere in their flow.</p>
<p>These guarantees apply to any unit of code from a statement to a
function, but are most commonly applied to member functions called
on objects. A point that is not often made relates exception safety
to encapsulation: not so much that exception safety can be improved
by better encapsulation, but that exception safety is one measure
of encapsulation. Prominent OO propaganda holds that encapsulation
is concerned with making object data private. Whilst this view is
not strictly false, it misses some important truths.</p>
<p>Encapsulation is neither a language feature nor a practice;
rather it is a non-functional property of code, and something that
you can have more or less of. Encapsulation describes the degree to
which something is self-contained, the degree to which its insides
affect its outsides, the degree to which internal representation
affects external usage. Encapsulation is about usability, about not
imposing on the user. Language features and idiomatic design
practices can be used to improve encapsulation, but of themselves
they are not encapsulation. Thinking back to exceptions, you can
see that without even thinking about internal representation, an
object that offers the strong guarantee on a member function is
more encapsulated than one that offers no guarantee.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e187" id="d0e187"></a>Incorruptible
Style</h3>
</div>
<p>It is one thing to have a guarantee, but quite another to
fulfill it. What is the style and mechanism of the code that allows
a thrown exception to propagate out of a block in a safe manner?
Including the degenerate case, there are essentially four
approaches to achieving exception safety:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="bold"><b>Exception-unaware code:</b></span></p>
<p>code that is not written with exceptions in mind is as easy to
read as it is dangerous - going wrong with confidence.</p>
</li>
<li>
<p><span class="bold"><b>Exception-aware code:</b></span></p>
<p>code may be scaffolded explicitly with <tt class=
"literal">try</tt>, <tt class="literal">catch</tt>, and <tt class=
"literal">throw</tt> to ensure that the appropriate stabilizing
action is taken in the event of a thrown exception. Alas, it is not
always obvious that exception-aware code is safe: such code is
rarely clear and concise.</p>
</li>
<li>
<p><span class="bold"><b>Exception-neutral code:</b></span></p>
<p>code that works in the presence of exceptions, but does not
require any explicit exception-handling apparatus to do so (i.e.,
no explicit <tt class="literal">try</tt>/<tt class=
"literal">catch</tt> code). Not only is exception-neutral code
briefer and clearer than exception-aware code, but it is also
typically shorter than exception unaware code. So, exception safety
and seamless exception propagation aside, such minimalism offers
another strong motivation for reworking code in this style.</p>
</li>
<li>
<p><span class="bold"><b>Exception-free code:</b></span></p>
<p>code that generates no exceptions offers the most transparent
fulfillment of exception safety.</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e232" id="d0e232"></a>When Cats
Turn Bad</h2>
</div>
<p>There is a tradition - from Schr&ouml;dinger to Stroustrup - of
employing cats for demonstration purposes, and I see no reason to
stand in the way of tradition. There appears to be sufficient prior
art in the stacking of cats [<a href="#Stroustrup">Stroustrup</a>]
that I will also adopt that practice. Of course, we are only
dealing with abstractions - if you are concerned for the poor cat,
keep in mind that unless we set it in concrete no act of cruelty
actually occurs.</p>
<p>Assuming that we have an appropriate <tt class=
"classname">cat</tt> class definition, the following fragment
demonstrates exception-unaware code:</p>
<pre class="programlisting">
{
  cat *marshall = new cat;
  .... // play with marshall
  delete marshall;
}
</pre>
<p>If an exception occurs during play, there will be a memory leak:
you will forget about your scoped <tt class="classname">cat</tt>.
The following fragment demonstrates exception-aware code:</p>
<pre class="programlisting">
{
  cat *marshall = new cat;
  try {
    .... // play with marshall
  }
  catch(...) {
    delete marshall;
    throw;
  }
  delete marshall;
}
</pre>
<p>Safe? Yes. Unreadable? Certainly. What it lacks in elegance it
more than makes up for in verbosity. The code may be safe, but it
is not obviously so [<a href="#Hoare">Hoare</a>]. The following
fragment demonstrates exception-neutral code:</p>
<pre class="programlisting">
{
  std::auto_ptr&lt;cat&gt; marshall(new cat);
  .... // play with marshall
}
</pre>
<p>For all its faults (and they are many), this is one job that
<tt class="classname">std::auto_ptr</tt> does do well. If we know
that default cat constructors do not throw exceptions, and we
recognize that marshall is always bounded by scope, the following
fragment demonstrates exception-free code:</p>
<pre class="programlisting">
{
  cat marshall;
  .... // play with marshall
}
</pre>
<p>Clearly, for demo purposes, we are taking some liberties with
the common understanding of cats and their care, treating them as
disposable commodities. Taking further license with feline
appreciation and object design, let us also assume that they are
value-based rather than entity-based objects. This means that they
support copying through construction and assignment, are generally
not heap based, and are typically not deeply involved in class
hierarchies.</p>
<p>Modern cloning technology is imperfect, so cat copy constructors
are not always guaranteed to work. On failure they throw an
exception, but they are well behaved enough to avoid resource
leakage and to not corrupt the program's state.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e272" id="d0e272"></a>Throwing
Gauntlets</h3>
</div>
<p>In 1994 Tom Cargill laid down a challenge - or extended an
invitation to solution, depending on your point of view -
concerning exception safety [<a href="#Cargill">Cargill</a>]. The
challenge was based on a fairly typical stack class template. There
were a number of elements to the challenge; the one I want to focus
on here is how to write the <tt class="methodname">pop</tt> member
function.</p>
<p>Here is some code that demonstrates the challenge:</p>
<pre class="programlisting">
template&lt;typename value_type&gt;
class stack {
public:
  void push(const value_type &amp;new_top) {
    data.push_back(new_top);
  }
  value_type pop() {
    value_type old_top = data.back();
    data.pop_back();
    return old_top;
  }
  std::size_t size() const {
    return data.size();
  }
  ....
private:
  std::vector&lt;value_type&gt; data;
};
</pre>
<p>I have used <tt class="classname">std::vector</tt> for brevity
(performing manual memory management does nothing to make the
problem clearer) and I am skipping issues related to assignment - I
would recommend looking at Herb Sutter's thorough coverage of the
challenge to see how this is addressed [<a href=
"#Sutter2000">Sutter2000</a>].</p>
<p>We can now recruit our favorite cat to demonstrate the issue.
First of all, pushing cats is not problematic:</p>
<pre class="programlisting">
stack&lt;cat&gt; stacked;
stacked.push(marshall);
std::cout &lt;&lt; &quot;number of stacked cats == &quot;
          &lt;&lt; stacked.size() &lt;&lt; std::endl;
</pre>
<p>The issue arises when we pop cats:</p>
<pre class="programlisting">
try {
  cat fender = stacked.pop();
  .... // play with fender
}
catch(...) {
  std::cout &lt;&lt; &quot;number of stacked cats&quot;
            &lt;&lt; &quot; == &quot; &lt;&lt; stacked.size()
            &lt;&lt; std::endl;
}
</pre>
<p>If the copy made in <tt class="methodname">pop</tt>'s return
statement fails, we have lost the top cat: the cat has been removed
from <tt class="varname">data</tt> and <tt class=
"varname">size</tt> is one less than before. <tt class=
"varname">pop</tt>, therefore, cannot satisfy the strong guarantee
of exception safety, because that requires everything to be left as
it was before the exception was thrown. The stack is still usable
and its resulting state is predictable, which means that we can
promise marginally more than the basic guarantee ... but we've
still got a missing cat.</p>
<p>Before setting about any solution, it is important to remember
that designs - and therefore design problems - do not exist in a
vacuum. Design is intimately bound up with purpose and context, and
without understanding these we risk either solving the wrong
problem or, as we so often do, solving the solution. Design is
about balancing goals - as well as cats.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e319" id="d0e319"></a>Unasking the
Question</h3>
</div>
<p>Looking at the class interface, we might ask why two actions are
combined into one: Why does <tt class="methodname">pop</tt> both
return a queried value and modify the target object? We know that
such a return causes an exception-safety problem, and we also know
that it is potentially wasteful. What if you do not plan to use the
return value? Even if you ignore it, the work that goes into
copying and returning the value still happens. You are potentially
paying both a cost and a penalty for something you didn't use.</p>
<p>The Command-Query Separation pattern [<a href=
"#Henney1">Henney1</a>] - sometimes referred to as a <span class=
"emphasis"><em>principle</em></span> rather than a <span class=
"emphasis"><em>pattern</em></span> [<a href="#Meyer">Meyer</a>] -
resolves our concerns by making a separation with respect to
qualification:</p>
<pre class="programlisting">
template&lt;typename value_type&gt;
class stack {
public:
  ....
  void pop() {
    data.pop_back();
  }
  value_type &amp;top() {
    return data.back();
  }
  const value_type &amp;top() const {
    return data.back();
  }
  ....
private:
  std::vector&lt;value_type&gt; data;
};
</pre>
<p>The separation of modifier from query operations ensures that we
cannot make a change and lose the result. This separated interface
also supports a slightly different usage model:</p>
<pre class="programlisting">
cat fender = stacked.top();
stacked.pop();
.... // play with fender
</pre>
<p>No copying exception can arise within the stack, so there is no
need to deal with it. This separation of concerns (and member
functions) can be seen in the design of the STL sequences and
sequence adaptors.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e349" id="d0e349"></a>Rephrasing the
Question</h3>
</div>
<p>It would seem that the problem is solved, except for one thing:
we never fully established the context of execution. It is entirely
possible that the basic guarantee of the original code was
satisfactory for our purposes, so there was no problem - from our
perspective - to be solved. Either we accept the loss of a cat or,
more commonly, the element type of the stack has exception-free
copying, which would be the case for built-in types as well as a
number of user-defined types. So under some circumstances, the
stack offers us the strong guarantee. If these are your
circumstances, the original code does not strictly speaking need to
be fixed. If they are not, there is indeed a problem to be fixed,
and Command-Query Separation offers one solution.</p>
<p>But there are others. Command-Query Separation is attractive
because it clarifies the role of interface functions. It could be
said to offer better encapsulation and cohesion. However, such a
statement is not universally true, and understanding why will
demonstrate why we must consider Command-Query Separation a pattern
(a design solution with consequences and a context) and not a
principle (an idea that expresses a universal truth).</p>
<p>Consider a clarification in design context: the stack is to be
shared between multiple threads. Ideally we would like to
encapsulate synchronization detail within the stack, ensuring that
primitives such as mutexes are used safely and correctly. Focusing
just on the push member, an exception-unaware implementation would
be as follows:</p>
<pre class="programlisting">
template&lt;typename value_type&gt;
class stack {
public:
  ....
  void push(const value_type &amp;new_top) {
    guard.lock();
    data.push_back(new_top);
    guard.unlock();
  }
  ....
private:
  mutable mutex monitor;
  std::vector&lt;value_type&gt; data;
};
</pre>
<p>The exception-neutral approach is both shorter and safer:</p>
<pre class="programlisting">
template&lt;typename value_type&gt;
class stack {
public:
  ....
  void push(const value_type &amp;new_top) {
    locker&lt;mutex&gt; guard(monitor);
    data.push_back(new_top);
  }
  ....
private:
  mutable mutex monitor;
  std::vector&lt;value_type&gt; data;
};
</pre>
<p>Where <tt class="classname">locker</tt> is a helper class
template responsible for abstracting control flow [<a href=
"#Henney2">Henney2</a>]:</p>
<pre class="programlisting">
template&lt;typename locked_type&gt;
class locker {
public:
  explicit locker(locked_type &amp;lockee)
    : lockee(lockee) {
    lockee.lock();
  }
  ~locker() {
    lockee.unlock();
  }
private:
  locker(const locker &amp;); // no copying
  locked_type &amp;lockee;
};
</pre>
<p>Making each public member function of <tt class=
"classname">stack</tt> self-locking would appear to preserve
encapsulation. However, this works only for usage scenarios that
are based on single function calls. For the Command-Query
Separation solution, this would introduce a couple of subtle
bugs:</p>
<pre class="programlisting">
cat fender = stacked.top();
stacked.pop();
.... // play with fender
</pre>
<p>First of all, <tt class="methodname">top</tt> returns a
reference. Consider the following simple action in another
concurrent thread:</p>
<pre class="programlisting">
stacked.pop();
</pre>
<p>Assuming that all of the member functions we are talking about
are self-locking, what is the problem? Imagine that the second
thread executes <tt class="methodname">pop</tt> just after the
first thread completes the call to <tt class="methodname">top</tt>:
the reference result from <tt class="methodname">top</tt> is now
dangling, referring to a non-existent element. Undefined behavior.
Oops. Poor <tt class="varname">fender</tt> gets a very bad start in
life.</p>
<p>Returning references to value objects from thread-shared objects
is a bad idea, so let's fix <tt class="classname">stack</tt>:</p>
<pre class="programlisting">
template&lt;typename value_type&gt;
class stack {
public:
  ....
  value_type top() const {
    locker&lt;mutex&gt; guard(monitor);
    return data.back();
  }
  ....
private:
  mutable mutex monitor;
  std::vector&lt;value_type&gt; data;
};
</pre>
<p>This solves the problem of undefined behavior, but leads us
straight into the jaws of the second problem, which is that of
&quot;surprising&quot; behavior. Idiomatically, we treat the following as a
single unit:</p>
<pre class="programlisting">
cat fender = stacked.top();
stacked.pop();
.... // play with fender
</pre>
<p>However, this usage is not cohesive in its execution. It can be
interrupted by another thread:</p>
<pre class="programlisting">
cat peavey;
stacked.push(peavey);
</pre>
<p>so that the <tt class="methodname">push</tt> in the second
thread occurs between the initialization of <tt class=
"varname">fender</tt> and the <tt class="methodname">pop</tt> in
the first thread. This means that the wrong element is popped from
the stack. Oops, again.</p>
<p>We could expose the <tt class="methodname">lock</tt> and
<tt class="methodname">unlock</tt> features in <tt class=
"classname">stack</tt> and let the user sort it all out:</p>
<pre class="programlisting">
template&lt;typename value_type&gt;
class stack {
public:
  void lock() {
    monitor.lock();
  }
  void unlock() {
    monitor.unlock();
  }
  ....
private:
  mutex monitor;
  std::vector&lt;value_type&gt; data;
};
</pre>
<p>Giving rise to the following somewhat clunky usage:</p>
<pre class="programlisting">
cat fender; {
  locker&lt; stack&lt;cat&gt; &gt; guard(stacked);
  fender = stacked.top();
  stacked.pop();
}
.... // play with fender
</pre>
<p>Let's compare this with the original usage:</p>
<pre class="programlisting">
cat fender = stacked.pop();
.... // play with fender
</pre>
<p>There's now more to write and more to remember - and therefore
more to forget. In addition to being more tedious and error prone,
it is easy to make the code pessimistic by forgetting to enclose
the <tt class="classname">locker</tt> in the narrowest scope
possible, leaving waiting threads locked out of <tt class=
"classname">stacked</tt> for far longer than necessary.</p>
<p>Remember that the original design's only safety shortcoming was
that it offered only the basic - rather than the strong - guarantee
of exception safety. It would take a leap of orthodoxy to say, hand
on heart, that Command-Query Separation has produced a more
cohesive and encapsulated solution - the opposite is true in this
context.</p>
<p>The Combined Method pattern [<a href="#Henney1">Henney1</a>] is
one that sometimes finds itself in tension with Command-Query
Separation, combining separate actions into a single, transactional
whole for the benefit of simplicity and correctness in,
principally, multithreaded environments. The original <tt class=
"methodname">pop</tt> was an example of this tactical pattern, but
suffered from weakened exception safety. An alternative realization
that achieves strong exception safety in an exceptionneutral style
is to overload the pure <tt class="methodname">pop</tt> function
with a Combined Method that takes a result argument:</p>
<pre class="programlisting">
template&lt;typename value_type&gt;
class stack {
public:
  ....
  void pop() {
    locker&lt;mutex&gt; guard(monitor);
    data.pop_back();
  }
  void pop(value_type &amp;old_top) {
    locker&lt;mutex&gt; guard(monitor);
    old_top = data.back();
    data.pop_back();
  }
  ....
private:
  mutable mutex monitor;
  std::vector&lt;value_type&gt; data;
};
</pre>
<p>This design tightens the screws a little on the element type
requirements, additionally requiring assignability as well as copy
constructibility. In practice this often means that we also demand
default constructibility of the target because the overloaded
<tt class="methodname">pop</tt> cannot be used in an
assignment:</p>
<pre class="programlisting">
cat fender;
stacked.pop(fender);
.... // play with fender
</pre>
<p>Another consequence of the assignment-based approach is that the
result variable must be an exact type match for the element type
(i.e., it cannot rely on implicit conversions that would have
worked if pop's result had been returned by value).</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e481" id="d0e481"></a>A Transactional
Approach</h3>
</div>
<p>Staying with Combined Method, but for brevity leaving aside the
code for thread synchronization, it turns out that it is possible
to write an exception-neutral version of <tt class=
"methodname">pop</tt> that preserves the original value-returning
interface and satisfies the strong guarantee of exception safety in
slightly different circumstances to the original:</p>
<pre class="programlisting">
template&lt;typename value_type&gt;
class stack {
public:
  ....
  value_type pop() {
    popper karl(data);
    return data.back();
  }
  ....
private:
  class popper {
  public:
    popper(std::vector&lt;value_type&gt; &amp;data)
      : data(data) {}
    ~popper() {
      if(!std::uncaught_exception())
        data.pop_back();
    }
  private:
    popper(const popper &amp;);
    std::vector&lt;value_type&gt; &amp;data;
  };
  std::vector&lt;value_type&gt; data;
};
</pre>
<p>Here a small helper object, <tt class="varname">karl</tt>, is
created to commit a <tt class="methodname">pop</tt> action if the
copying of the return value is successful. The <tt class=
"classname">popper</tt> object is passed the representation of the
surrounding stack, and on destruction, it will cause a <tt class=
"methodname">pop_back</tt> to be executed. If the copy is
unsuccessful, the popper destructor will not commit the intended
change, skipping the <tt class="methodname">pop_back</tt>.</p>
<p>This approach has the benefit of preserving the signature
interface and typically reducing the number of temporaries involved
in copying. However, there is an important precondition that must
be publicized and satisfied for <tt class="classname">popper</tt>
to work as expected: <tt class="methodname">pop</tt> should not be
called from the destructor of another object. Why? What if the
destructor is being called because the stack is being unwound by an
exception? The call to <tt class=
"function">std::uncaught_exception</tt> in <tt class=
"classname">popper</tt>'s destructor will return true even if the
copy is successful.</p>
<p>How you respond to this scenario is a matter of context-driven
requirement. Either you state that the behavior of a <tt class=
"classname">stack</tt> is undefined in these circumstances or you
define behavior for it. One definition of behavior is shown above -
in the presence of existing exceptions, don't pop - but could be
considered unsatisfactory because of its pessimism. An alternative,
more optimistic approach is to say that our <tt class=
"methodname">pop</tt> offers a strong guarantee of exception safety
if there is no unhandled exception present when it is executed, but
only the basic guarantee otherwise:</p>
<pre class="programlisting">
template&lt;typename value_type&gt;
class stack {
  ....
  class popper {
  public:
    popper(std::vector&lt;value_type&gt; &amp;data)
      : data(data),
        unwinding(
            std::uncaught_exception()) {}
    ~popper() {
      if(unwinding
         || !std::uncaught_exception())
        data.pop_back();
    }
  private:
    popper(const popper &amp;);
    std::vector&lt;value_type&gt; &amp;data;
    const bool unwinding;
  };
  ....
};
</pre>
<p><tt class="function">std::uncaught_exception</tt> is a function
that is generally not as useful as it first appears. It often leads
to false confidence in code [<a href="#Sutter2002">Sutter2002</a>],
but with an understanding of its limitations, there are a few
situations in which we can press it into useful service.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e539" id="d0e539"></a>A Lazy
Approach</h3>
</div>
<p>It is possible to take the transactional idea a step further
using a technique that I first saw Angelika Langer present at
<span class="emphasis"><em>C++ World</em></span> in 1999:</p>
<pre class="programlisting">
template&lt;typename value_type&gt;
class stack {
public:
  ....
  value_type pop() {
    try {
      --length;
      return data[length];
    }
    catch(...) {
      ++length;
      throw;
    }
  }
  ....
private:
  std::size_t length;
  std::vector&lt;value_type&gt; data;
};
</pre>
<p>Here the size of the stack is tracked in a separate variable
that is incremented and decremented accordingly. It uses an
exception-aware style to implement commit-rollback semantics,
bumping the length count back up again if the copy from the last
element fails with an exception.</p>
<p>The obvious benefit of this approach is that it will work
independently of whether or not the stack is already unwinding
because of an exception. However, the disadvantage with this
approach is not so much with the extra piece of state that has been
introduced but that popped elements are never actually popped. They
continue to exist in the <tt class="varname">data</tt> member long
after they have been popped: at least up until another modification
operation requires rationalization of <tt class="varname">data</tt>
with <tt class="varname">length</tt>, such as a push. A couple of
minor refinements address this issue by introducing a deferred but
amortized commit operation:</p>
<pre class="programlisting">
template&lt;typename value_type&gt;
class stack {
public:
  stack()
    : uncommitted(false) {}
  void push(const value_type &amp;new_top) {
    commit();
    data.push_back(new_top);
  }
  value_type pop() {
    commit();
    try {
      uncommitted = true;
      return data.back();
    }
    catch(...) {
      uncommitted = false;
      throw;
    }
  }
  std::size_t size() const {
    commit();
    return data.size();
  }
  ....
private:
  void commit() const {
    if(uncommitted) {
      data.pop_back();
      uncommitted = false;
    }
  }
  mutable bool uncommitted;
  mutable std::vector&lt;value_type&gt; data;
};
</pre>
<p>Internally the committed state will be at most one element
different from the uncommitted state, but externally any attempt to
determine the state by calling an operation will ensure that the
books are kept balanced. This constraint requires that all public
functions call the <tt class="methodname">commit</tt> function as
their first act, which requires that the object's state to be
qualified as <tt class="literal">mutable</tt> to permit updates in
query functions. Thus, this design affects all member functions and
imposes a little more on the class developer. The class user is,
however, unaffected.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e572" id=
"d0e572"></a>Conclusion</h2>
</div>
<p>It is time to declare a moratorium on these exceptional
experiments on abstracted cats. They have served to demonstrate
that no design can be perfect, and that encapsulation is related to
usability; it is not just a matter of data hiding. Although we may
strive for absolute recommendations, there are times when only
relative ones can be made with confidence (and caveats). Design is
about compromise and about context, and therefore it is about
understanding consequences. Weigh up the benefits and liabilities
for a particular usage and then make your decision - what is
workable in one context may be unworkable in another, and so what
is &quot;good&quot; in one situation may be &quot;bad&quot; in another.</p>
<p>On the compromise of design in other fields I will leave you
with this quote from David Pye [<a href=
"#Petroski">Petroski</a>]:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>It follows that all designs for use are arbitrary. The designer
or his client has to choose in what degree and where there shall be
failure. Thus the shape of all design things is the product of
arbitrary choice. If you vary the terms of your compromise - say,
more speed, more heat, less safety, more discomfort, lower first
cost-then you vary the shape of the thing designed. It is quite
impossible for any design to be &quot;the logical outcome of the
requirements&quot; simply because, the requirements being in conflict,
their logical outcome is an impossibility.</p>
</blockquote>
</div>
<div class="sidebar">
<p>This article was originally published on the C/C++ Users Journal
C++ Experts Forum in February 2002 at <a href=
"http://www.cuj.com/experts/documents/s=7986/cujcexp2002Henney/"
target=
"_top">http://www.cuj.com/experts/documents/s=7986/cujcexp2002Henney/</a></p>
<p>Thanks to Kevlin for allowing us to reprint it.</p>
</div>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e592" id="d0e592"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Taligent" id="Taligent"></a>
<p class="bibliomixed">[Taligent] <span class="citetitle"><i class=
"citetitle">Taligent's Guide to Designing Programs: Well-Mannered
Object-Oriented Design in C++</i></span>, (Addison-Wesley, 1994),
<span class="bibliomisc"><a href=
"http://pcroot.cern.ch/TaligentDocs/TaligentOnline/DocumentRoot/1.0/Docs/books/WM/WM_1.html"
target=
"_top">http://pcroot.cern.ch/TaligentDocs/TaligentOnline/DocumentRoot/1.0/Docs/books/WM/WM_1.html</a></span></p>
</div>
<div class="bibliomixed"><a name="Fowler" id="Fowler"></a>
<p class="bibliomixed">[Fowler] Martin Fowler. <span class=
"citetitle"><i class="citetitle">Refactoring: Improving the Design
of Existing Code</i></span> (Addison-Wesley, 1999), <span class=
"bibliomisc"><a href="http://www.refactoring.com" target=
"_top">www.refactoring.com</a></span></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 class="bibliomixed"><a name="Stroustrup" id="Stroustrup"></a>
<p class="bibliomixed">[Stroustrup] Bjarne Stroustrup. &quot;Sixteen
Ways to Stack a Cat,&quot; <span class="citetitle"><i class=
"citetitle">C++ Report</i></span>, October 1990, <span class=
"bibliomisc"><a href="http://www.research.att.com/~bs" target=
"_top">www.research.att.com/~bs</a></span></p>
</div>
<div class="bibliomixed"><a name="Hoare" id="Hoare"></a>
<p class="bibliomixed">[Hoare] <span class="bibliomisc">To quote C.
A. R. Hoare: &quot;<span class="quote">There are two ways of
constructing a software design. One way is to make it so simple
that there are obviously no deficiencies. And the other way is to
make it so complicated that there are no obvious
deficiencies.</span>&quot;</span></p>
</div>
<div class="bibliomixed"><a name="Cargill" id="Cargill"></a>
<p class="bibliomixed">[Cargill] Tom Cargill. &quot;Exception Handling:
A False Sense of Security,&quot; <span class="citetitle"><i class=
"citetitle">C++ Report</i></span>, November-December 1994.</p>
</div>
<div class="bibliomixed"><a name="Henney1" id="Henney1"></a>
<p class="bibliomixed">[Henney1] Kevlin Henney. &quot;A Tale of Two
Patterns,&quot; <span class="citetitle"><i class="citetitle">Java
Report</i></span>, December 2000, <span class="bibliomisc"><a href=
"http://www.curbralan.com" target=
"_top">www.curbralan.com</a></span></p>
</div>
<div class="bibliomixed"><a name="Meyer" id="Meyer"></a>
<p class="bibliomixed">[Meyer] Bertrand Meyer. <span class=
"citetitle"><i class="citetitle">Object-Oriented Software
Construction, 2nd Edition</i></span> (Prentice Hall, 1997).</p>
</div>
<div class="bibliomixed"><a name="Henney2" id="Henney2"></a>
<p class="bibliomixed">[Henney2] Kevlin Henney. &quot;C++ Patterns:
Executing Around Sequences,&quot; <span class="citetitle"><i class=
"citetitle">EuroPLoP 2000</i></span>, July 2000, <span class=
"bibliomisc"><a href="http://www.curbralan.com" target=
"_top">www.curbralan.com</a></span></p>
</div>
<div class="bibliomixed"><a name="Sutter2002" id="Sutter2002"></a>
<p class="bibliomixed">[Sutter2002] Herb Sutter. <span class=
"citetitle"><i class="citetitle">More Exceptional C++</i></span>
(Addison-Wesley, 2002).</p>
</div>
<div class="bibliomixed"><a name="Petroski" id="Petroski"></a>
<p class="bibliomixed">[Petroski] Henry Petroski. <span class=
"citetitle"><i class="citetitle">To Engineer is Human: The Role of
Failure in Successful Design</i></span> (Vintage, 1992).</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;cats, curling, exceptions</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
