    <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  :: The Curate's Wobbly Desk</title>
        <link>https://members.accu.org/index.php/articles/301</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">Programming Topics + Overload Journal #70 - Dec 2005</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/c65/">Programming</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/c142/">70</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+142/">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;The Curate's Wobbly Desk</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 December 2005 05:00:00 +00:00 or Fri, 02 December 2005 05:00:00 +00: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>The Vicar's
Lodger</h2>
</div>
<p>The story of the curate's egg is well known [<a href=
"#story">story</a>], but I bet you've never heard about the
curate's wobbly desk.</p>
<p>When Aubrey Jones was first ordained he was appointed curate to
St Michael's church, Belton Braces. It was a small parish serving
just a few quiet hamlets and there would have been nowhere for Mr.
Jones to stay if he had not been offered lodgings at the vicarage.
The vicar, the Reverend Cuthbert Montague-Smith, was a large and
imposing man with strong opinions on how to do God's bidding. The
timid Aubrey Jones found him rather... well, intimidating.</p>
<p>The bishop had suggested that Aubrey would benefit from studying
the early history of the Christian church and the vicar expressed a
hope that this research would turn up some interesting material for
the parish magazine. Eager to please, Aubrey went out and bought a
cheap, mass-produced, self-assembly desk to work at. The D.I.Y.
shop was running a special offer - free delivery - and the curate
felt he was getting a bargain.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e30" id="d0e30"></a>Secret
Drawers</h2>
</div>
<p>Reading through the assembly instructions Aubrey was delighted
to find that the desk contained a secret drawer. He had fond
notions of keeping a diary and one day, perhaps, writing a book on
the life of an English pastor based on his own ministry and
experiences. But he suspected that Cuthbert would regard such
activities as of little practical value and it would be better for
the vicar to remain ignorant of those particular jottings.</p>
<p>As chance would have it, the vicar's desk also had a secret
drawer. I don't know what Cuthbert kept in that drawer, or even if
he knew it was there. But I do know that both Aubrey's and
Cuthbert's secret drawers were operated by two catches. If you
press both catches at the same time the drawer slides out. I
remembered the vicar, the curate and the secret drawers when I was
working on the software for a computer game. (It would have been
called &quot;Murder at the Vicarage&quot;, but Agatha Christie got there
first.) &quot;Let's use that in the game&quot;, I thought, and wrote an
interface class representing the secret drawer based on classes
from my Event/Callback library [<a href="#Bass">Bass</a>]. Listing
1 shows the Event class template used for the drawer release
mechanism and the <tt class="classname">Callback::Function</tt>
class template used for the catches.</p>
<div class="sidebar">
<pre class="programlisting">
// Event classes.
template&lt; typename Arg &gt;
struct Event : std::list&lt; Callback::Function&lt;Arg&gt;* &gt;
{
  typedef Arg                     argument_type;
  typedef Callback::Function&lt;Arg&gt; callback_type;
  void notify( Arg arg )
  {
    std::for_each( this-&gt;begin(), this-&gt;end(),
       bind_2nd(
          memfun( &amp;callback_type::operator()),
          arg ));
  }
};
// Callback function base classes.
namespace Callback
{
  template&lt; typename Arg &gt;
  struct Function
  {
    typedef Arg argument_type;
    virtual ~Function() {}
    virtual void operator() ( argument_type ) = 0;
  };
}
</pre>
<p><span class="bold"><b>Listing 1 - the Event and
Callback::Function classes.</b></span></p>
</div>
<p>The <tt class="classname">Drawer</tt> class interface is shown
in Listing 2. The key feature here is that <tt class=
"classname">Digital_Input</tt> is an abstract base class with a
pure virtual function call operator. When catch A's <tt class=
"classname">Digital_Input</tt> callback is invoked the lock/unlock
state for catch A must be updated, the state of catch B must be
read and, if both catches are in the unlock position, the drawer
release mechanism must be activated by triggering the <tt class=
"classname">Digital_Output</tt> event. The overall effect is that
the <tt class="classname">Drawer</tt> class behaves like an And
gate in an electronic circuit.</p>
<div class="sidebar">
<pre class="programlisting">
// A value type with just two values.
enum Digital_Value { off, on };

// Input and output types.
typedef Callback::Function&lt; Digital_Value &gt;
   Digital_Input;
typedef Event&lt; Digital_Value &gt; Digital_Output;

// A secret drawer operated by two catches.
class Drawer
{
public:
    Drawer();
    Digital_Input&amp; catch_A();  // catch A
    Digital_Input&amp; catch_B();  // catch B
    Digital_Output&amp; output();  // drawer release
private:
    . . .
};
</pre>
<p><span class="bold"><b>Listing 2 - Secret drawer
interface.</b></span></p>
</div>
<p>In the game, a <tt class="classname">Drawer</tt> object is
created and GUI push-button widgets are attached to the drawer's
inputs (the catches). The drawer itself is represented by an
<tt class="classname">Image</tt> widget which shows either a closed
drawer or an open drawer. A callback that toggles between the open
and closed images is attached to the drawer's output (the drawer
release mechanism). The player has to find a way of pressing both
of the catches at the same time to open the drawer - not easy using
just a mouse. A rough sketch of the client code is shown in Listing
3.</p>
<div class="sidebar">
<pre class="programlisting">
// Internal objects.
Drawer drawer;                       // secret drawer

// User interface.
GUI::Button  catch_A, catch_B;       // buttons to release the drawer
GUI::Image   picture;                // picture of open/closed drawer
Toggle_Image toggle_image(picture);  // functor that toggles open/closed

// Connect the UI widgets to the internal objects.
catch_A.push_back( &amp;drawer.catch_A() );
catch_B.push_back( &amp;drawer.catch_B() );
drawer.output().push_back( &amp;toggle_picture );

// Run the GUI scheduling loop.
GUI::run();
</pre>
<p><span class="bold"><b>Listing 3 - Using the Drawer
class.</b></span></p>
</div>
<p>The rest of this paper describes two ways of implementing the
Drawer class with the help of our curate, his vicar and their
furniture.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e89" id="d0e89"></a>The Curate's
Self-Assembly Desk</h2>
</div>
<p>As soon as he had a spare half-hour Aubrey Jones opened the box
containing his flat-pack desk, carefully laid out the panels,
runners, feet, dowels, nuts and bolts, and began to assemble them.
He paid particular attention to the secret drawer. The drawer
itself had a grain-effect finish that looked remarkably like real
wood, but probably wasn't. The release mechanism was an integral
part of the drawer, located at the back. The secret catches were
separate - metal, with knobs in the same fake wood as the drawer
and disguised as decorative features. The catches had to be
fastened to the front of the drawer and connected to the release
mechanism with two long, thin and worryingly flimsy metal rods.</p>
<p>The structure of my code was very similar, as you can see from
the overview in Listing 4 and the function bodies in Listing 5. The
drawer release mechanism was represented by <tt class=
"classname">Digital_Value</tt> and <tt class=
"classname">Digital_Output</tt> members of the <tt class=
"classname">Drawer</tt> class. The catches were separate classes
(<tt class="classname">Catch_A</tt> and <tt class=
"classname">Catch_B</tt>) and they were attached to the <tt class=
"classname">Drawer</tt> class by pointers. With this design the
functions in the public interface are trivial and shown here
defined within the class declaration.</p>
<div class="sidebar">
<pre class="programlisting">
class Drawer
{
public:
  Drawer();
  Digital_Input&amp; catch_A() { return catch_A_input; }
  Digital_Input&amp; catch_B() { return catch_B_input; }
  Digital_Output&amp; output() { return output_event; }
private:
  struct Catch_A : Digital_Input
  {
    Catch_A( Drawer* d ) : value( off ), drawer( d ) {}
    void operator()( Digital_Value );
    Digital_Value value;
    Drawer* const drawer;
  };
  struct Catch_B : Digital_Input
  {
    // . . . same as Catch_A . . .
  };
  void sync();    // set output value from inputs
  Catch_A        catch_A_input;  // catch A's lock/unlock state
  Catch_B        catch_B_input;  // catch B's lock/unlock state
  Digital_Value  output_value;  // drawer release state
  Digital_Output output_event;  // drawer release event
};
</pre>
<p><span class="bold"><b>Listing 4 - Overview of the Drawer with
separate Catch classes.</b></span></p>
</div>
<div class="sidebar">
<pre class="programlisting">
// Operate Catch A
inline void Drawer::Catch_A::operator()( Digital_Value value )
{
  drawer-&gt;catch_A_input.value = value;
  drawer-&gt;sync();
}
// Operate Catch B
inline void Drawer::Catch_B::operator()( Digital_Value value )
{
  drawer-&gt;catch_B_input.value = value;
  drawer-&gt;sync();
}
// Create the Drawer
inline Drawer::Drawer()
  : catch_A_input( this ), catch_B_input( this ), output_value( off )
{}
// Set and publish the state of the drawer release mechanism
inline void Drawer::sync()
{
  output_value = 
     Digital_Value( catch_A_input.value &amp; catch_B_input.value );
  output_event.notify( output_value );
}
</pre>
<p><span class="bold"><b>Listing 5 - Implementation of the Drawer
with separate Catch classes.</b></span></p>
</div>
<p>This design is conceptually simple, but it didn't feel quite
right. Like cheap, mass-produced furniture it seemed inelegant and
unsatisfying. Did the <tt class="classname">Catch</tt> classes
really have to store a pointer to their parent object? After all,
the address of the <tt class="classname">Drawer</tt> object is a
fixed offset from each of the <tt class="classname">Catch</tt>
objects. Couldn't we just subtract that offset from the <tt class=
"classname">Catch</tt> object's this pointer and apply a suitable
cast?</p>
<p>After some thought I decided that pointer arithmetic and casting
would be worse than the disease I was trying to cure. A case of
premature optimisation, and an ugly one at that. I needed to think
like the master craftsmen of old. And that reminded me of the
vicar's desk.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e142" id="d0e142"></a>The Vicar's
Antique Writing Table</h2>
</div>
<p>Cuthbert Montague-Smith loved his big sturdy old desk. It was
reminiscent of the magnificent library writing table at Harewood
House, near Leeds [<a href="#chippendale">chippendale</a>].
Cuthbert suspected it was built by Thomas Chippendale himself,
although he was unable to provide a shred of evidence to support
that view.</p>
<p>I don't suppose the great furniture maker would appreciate the
finer points of software design in C++, but I tried to imagine the
approach he would use. He would surely pay considerable attention
to detail and not rest until he had discovered a method that was
both elegant and practical.</p>
<p>With this in mind I thought again about the <tt class=
"classname">Drawer</tt> class implementation. The curate's desk
design in Listings 4 and 5 contains <tt class=
"classname">Catch</tt> classes that reference an external object
(the <tt class="classname">Drawer</tt> itself); that is why it
needs those inelegant pointers. If we could move the external data
into the <tt class="classname">Catch</tt> classes the pointers
would not be necessary. So the question is, how can we make the
<tt class="classname">Drawer</tt> state variables part of two
separate <tt class="classname">Catch</tt> objects?</p>
<p>It's no good putting member variables into the concrete
<tt class="classname">Catch</tt> classes because that would just
duplicate the data; and we can't put data into the <tt class=
"classname">Digital_Input</tt> class because that would compromise
the Event/Callback library. The only option is to put them in a
shared base class. The key to the desk is virtual
inheritance.<sup>[<a name="d0e180" href="#ftn.d0e180" id=
"d0e180">1</a>]</sup> Listing 6 and Listing 7 show how I chose to
use this technique.</p>
<div class="sidebar">
<pre class="programlisting">
class Drawer
{
public:
  . . .
private:
  struct Data
  {
    Data();
    void sync();
    Digital_Value  catch_A_value,
                   catch_B_value;
    Digital_Value  output_value;
    Digital_Output output_event;
  };
  struct Catch_A : Digital_Input, virtual Data
  {
    void operator()( Digital_Value );
  };
  struct Catch_B : Digital_Input, virtual Data
  {
    void operator()( Digital_Value );
  };
  struct Body : Catch_A, Catch_B {} body;
};
</pre>
<p><span class="bold"><b>Listing 6 - Overview of the Drawer using
virtual inheritance.</b></span></p>
</div>
<div class="sidebar">
<pre class="programlisting">
// Operate Catch A
inline void Drawer::Catch_A::operator()(
   Digital_Value value )
{
  catch_A_value = value;
  sync();
}
// Operate Catch B
inline void Drawer::Catch_B::operator()(
   Digital_Value value )
{
  catch_B_value = value;
  sync();
}
// Initialise the Drawer's state
inline Drawer::Data::Data()
   : catch_A_value( off ),
   catch_B_value( off ),
   output_value( off )
{}
// Set and publish the state of the drawer 
// release mechanism
inline void Drawer::Data::sync()
{
  output_value = Digital_Value(
     catch_A_value &amp; catch_B_value );
  output_event.notify( output_value );
}
</pre>
<p><span class="bold"><b>Listing 7 - Implementation of the Drawer
using virtual inheritance.</b></span></p>
</div>
<p>All the variables have been moved to the private nested class,
<tt class="classname">Data</tt>. As this is an implementation
detail of the <tt class="classname">Drawer</tt> class I have not
bothered to create separate interface and implementation sections
for <tt class="classname">Data</tt>. Purists can add a private
section and suitable access functions if they wish. It is
appropriate, however, to provide <tt class="classname">Data</tt>
with a constructor and a function that sets the drawer release
mechanism's state from the <tt class="classname">Catch</tt> values
to avoid duplicating these operations in both the <tt class=
"classname">Catch</tt> classes.</p>
<p>The <tt class="classname">Catch</tt> classes themselves use
virtual inheritance to &quot;import&quot; the shared <tt class=
"classname">Data</tt> object. They also provide a function that
updates their own lock/unlock state, calculates the drawer release
state and publishes the drawer release state to the client
code.</p>
<p>The <tt class="classname">Drawer</tt> class could inherit
directly from the <tt class="classname">Catch</tt> classes, but
that would mean exposing the <tt class="classname">Data</tt> class
and the concrete <tt class="classname">Catch</tt> classes to its
clients. Instead, I have chosen to write a nested <tt class=
"classname">Body</tt> class that completes the virtual inheritance
diamond and then store a <tt class="classname">Body</tt> member
within the <tt class="classname">Drawer</tt> class. That way, none
of the classes used in the <tt class="classname">Drawer</tt>
implementation pollute the namespaces used in the client code.</p>
<p>The <tt class="classname">Catch</tt> class member functions in
the vicar's desk design are slightly simpler than those in the
curate's version. Moving the data to a base class enables them to
access the variables directly instead of via those ugly and
unnecessary pointers. Initialisation of the data members is also
slightly simpler because there are no pointer values to set (which
means one less opportunity for a bug). And the sync() function is
the same in both designs. Chippendale would have been proud.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e255" id="d0e255"></a>It All Falls
Apart</h2>
</div>
<p>The curate struggled to assemble his desk. The instructions
seemed to have been translated from a foreign language (badly), the
diagrams didn't seem to match the parts he had and Aubrey Jones'
mind wasn't good at 3D visualisation. The release mechanism for the
secret drawer, in particular, baffled the poor man. Eventually, the
desk was completed and moved into position under the window of
Aubrey's bed sitting room where he could look out over the
garden.</p>
<p>The desk was always a bit wobbly and the secret drawer never did
work. (The connecting rods were not installed correctly, so the
drawer release would not activate.) Aubrey never quite found the
time to research the early history of the Christian church and with
no place to hide his private writings he soon lost the urge to keep
a diary. Indeed, after a few years as the vicar of a provincial
parish on the borders of London and Essex his ecclesiastical career
took a turn for the worse [<a href="#genesis">genesis</a>]. He may
yet write a book. If he does, it will be about temptation, greed
and the frailty of man, but sadly it will not be about a life of
service to the church.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e265" id="d0e265"></a>References</h2>
</div>
<div class="bibliomixed"><a name="story" id="story"></a>
<p class="bibliomixed">[story] See <span class=
"bibliomisc"><a href="http://www.worldwidewords.org/qa/qa-cur1.htm"
target=
"_top">http://www.worldwidewords.org/qa/qa-cur1.htm</a></span>, for
example.</p>
</div>
<div class="bibliomixed"><a name="Bass" id="Bass"></a>
<p class="bibliomixed">[Bass] Phil Bass, &quot;Evolution of the Observer
Pattern&quot;, Overload 64, December 2004.</p>
</div>
<div class="bibliomixed"><a name="chippendale" id=
"chippendale"></a>
<p class="bibliomixed">[chippendale] <span class=
"bibliomisc"><a href=
"http://www.harewood.org/chippendale/index2.htm" target=
"_top">http://www.harewood.org/chippendale/index2.htm</a></span></p>
</div>
<div class="bibliomixed"><a name="genesis" id="genesis"></a>
<p class="bibliomixed">[genesis] <span class="bibliomisc"><a href=
"http://www.lyricsfreak.com/g/genesis/58843.html" target=
"_top">http://www.lyricsfreak.com/g/genesis/58843.html</a></span></p>
</div>
</div>
<div class="footnotes"><br>
<hr class="c3" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e180" href="#d0e180" id=
"ftn.d0e180">1</a>]</sup> I claim poetic licence for bending the
rules of English grammar here.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
