    <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  :: Exploring Patterns 3 - The Adapter</title>
        <link>https://members.accu.org/index.php/journals/585</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 #28 - Oct 1998 + Design of applications and programs</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/c175/">28</a>
                    (10)
<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/c67/">Design</a>
                    (236)
<br />

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

                    -                        <a href="https://members.accu.org/index.php/journals/c175+67/">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;Exploring Patterns 3 - The Adapter</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 27 October 1999 18:23:02 +01:00 or Wed, 27 October 1999 18:23:02 +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>It was nice to learn from John Merrells that my last article
fired at least one reader to add a contribution. If you remember,
one of the main purposes I have in writing these articles is to
help me develop my understanding of various patterns. It is in my
nature to fire off various ideas when I am in exploration mode. If
I am lucky a few of them will be worthwhile and have more than a
transient existence. Even the bad ideas have the advantage of
exercising a few brain cells; yours as well as mine.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e22" id="d0e22"></a>The Adapter
Pattern</h2>
</div>
<p>The fundamental idea behind the Adapter pattern is being able to
provide a tailor made interface to allow reuse of existing code
(and a secondary form in which code is tailored to an existing
interface). <i class="citetitle">Design Patterns</i> limits its
discussion to classes (or the equivalent in other OO languages).
Let me start with a couple of simpler instances using
functions.</p>
<p>Several functions in the Standard C Library are seriously flawed
in that they are not <tt class="literal">const</tt> correct. For
example the prototype for <tt class="function">strpbrk</tt> is:</p>
<pre class="programlisting">
char *strpbrk(char const *s1, char const *s2);
</pre>
<p>Unless no character from <tt class="varname">s2</tt> occurs in
<tt class="varname">s1</tt> (when <tt class=
"function">strpbrk()</tt> returns a null pointer) this function
unfortunately removes <tt class="literal">const</tt> qualification.
How should we write it in C++? Try as you might, you will find that
you cannot implement this C function as a single C++ function. Well
I tell a lie, you could forcibly remove the <tt class=
"literal">const</tt> qualification with a cast.</p>
<p>If we remove the <tt class="literal">const</tt> qualification
from the first parameter we cannot call that version with a
traditional <tt class="literal">const</tt> C string (array of
<tt class="type">char</tt>). That will certainly break some legacy
code where the programmer passes a <tt class="literal">const</tt>
qualified array of <tt class="type">char</tt> to <tt class=
"function">strpbrk()</tt>. What we need is two functions with the
following prototypes:</p>
<pre class="programlisting">
char const *
      strpbrk(char const *s1, char const *s2);
char *strpbrk(char * s1, char const * s2);
</pre>
<p>Overloading will resolve the call to preserve the appropriate
qualification. I guess this will still break some C code, but such
code will already be broken in that it will try to write to a
string that was already (prior to the call to <tt class=
"function">strpbrk()</tt>) read only. I am not worried about such
breakage, all that a C++ compiler will be doing is highlighting a
potential problem in the existing code.</p>
<p>Now any self-respecting programmer is going to feel less than
happy with writing two identical function bodies simply to maintain
<tt class="literal">const</tt> correctness. There is no need for
separate implementation just different interfaces (prototypes). The
maximal <tt class="literal">const</tt> version is all we need to
implement. By itself it will work for any string (well any
non-<tt class="literal">volatile</tt> string). The only problem is
that passing a string through such a function adds a superfluous
<tt class="literal">const</tt> qualification if there was none at
entry. Fortunately we can write a simple adapter function to
resolve this problem:</p>
<pre class="programlisting">
inline char *
strpbrk(char * s1, char const * s2)
{
  return const_cast&lt;char *&gt;
    (strpbrk(const_cast&lt;char const *&gt;
                              (s1), s2));
}
</pre>
<p>In other words we forcibly add <tt class="literal">const</tt>
qualification to the first argument to get the all <tt class=
"literal">const</tt> version selected and then forcibly remove it
from the return. As this version will only be called for a writable
first argument, removing the <tt class="literal">const</tt>
qualification cannot introduce some new danger.</p>
<p>There are many examples where this mechanism makes sense.
Consider the common idiom where a member function returns a
reference to the object:</p>
<pre class="programlisting">
MyType &amp; MyType::func()
{
  // functionality
  return *this;
}
</pre>
<p>Fine, but what happens when this is a <tt class=
"literal">const</tt> member function? That's right, you get an
added <tt class="literal">const</tt> qualification. This can be
fixed in the same way:</p>
<pre class="programlisting">
MyType const &amp; MyType::func() const
{
  // functionality
  return *this;
}
</pre>
<p>coupled with (almost certainly in class):</p>
<pre class="programlisting">
MyType &amp; func()
{  
  return
    const_cast&lt;MyType&gt; 
    (const_cast&lt;MyType const *&gt;
    (this)-&gt;func());
}
</pre>
<p>This mechanism may not yet be an idiom of C++ but if not, it
ought to be. It would be nice to turn this into a template but I
cannot see anyway of doing so. That may just be my lack of
insight.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e131" id="d0e131"></a>Overloaded C
Functions</h3>
</div>
<p>The coming version of C will include support libraries for both
<tt class="type">float</tt> and <tt class="type">long double</tt>
as well as the already existing support for <tt class=
"type">double</tt>. Leaving aside what some will consider an
elegant method to avoid overloading in C (others will consider it
an atrocious hack) the true names of the maths functions will
identify their precision. For example <tt class=
"function">sin()</tt> will take and return a <tt class=
"type">double</tt>, <tt class="function">fsin()</tt> will take and
return a <tt class="type">float</tt> and <tt class=
"function">lsin()</tt> will take and return a <tt class="type">long
double</tt>. (By the way, if the introduction of these extra
identifiers breaks your code, the problem is yours because ISO/IEC
9899:1990 7.13.4 reserved all the names of existing functions in
<tt class="filename">math.h</tt> when prefixed with <tt class=
"literal">f</tt> or <tt class="literal">l</tt>).</p>
<p>The problem for C++ is that C's fancy footwork to allow the
compiler to choose what it thinks you want when you write
<tt class="literal">sin(0.12F)</tt> is far from how we would do it
in C++. What we need is some adapter functions to take the C
distinct names and create a C++ overloaded set of functions. So we
will have:</p>
<pre class="programlisting">
double sin (double);  // implemented as in C
inline float sin (float angle)
{ return fsin(angle);}
inline long double sin(long double angle) 
{ return lsin(angle);}
</pre>
<p>In other words, if you need a set of overloaded functions that
can be used in C you must first write them with distinct names
(qualified as <tt class="literal">extern &quot;C&quot;</tt>) and then add
adapter functions to provide the overloading if you want to use
them in C++.</p>
<p>As these adapter functions are straight forwarding functions
(sometimes called wrappers) I cannot think of a good reason to not
inline them.</p>
<p>As a general principle, when I want a function to be useable in
both C and C++ I would give careful consideration to declaring and
defining a C version with a distinct name and then using an adapter
to provide an equivalent type-safe C++ version. I think that this
would reduce surprises when na&iuml;ve C programmers do not realise
that the version of an overloaded function they are calling will
have been name mangled in the object code. Please note, I said
careful consideration not that this is the only correct way to do
it.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e188" id="d0e188"></a>Adapters for
classes</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e191" id="d0e191"></a>Changing or
Enhancing an Existing Interface</h3>
</div>
<p>Let me start with a very simple adapter (mainly because it
includes a nasty gotcha pointed out to me by Michael Ball). Suppose
I have a class that I want to use as a base class for a polymorphic
hierarchy but the original author failed to provide any virtual
functions. In particular it does not include a virtual destructor.
A simple solution comes to mind:</p>
<pre class="programlisting">
class PolyBase: public Base
{
public:
  virtual ~PolyBase(){};
};
</pre>
<p>This is about the simplest class adapter that you can imagine.
Of course, in practice, you will add quite a few <tt class=
"literal">virtual</tt> qualified forwarding functions (adapter
functions) to provide polymorphism for existing functionality. Note
that you haven't apparently added any data to <tt class=
"classname">PolyBase</tt>, so you might think that you could
happily use this global/namespace function:</p>
<pre class="programlisting">
Base &amp; func();
</pre>
<p>Which returns a <tt class="classname">Base</tt> object by
reference. You might try this for example:</p>
<pre class="programlisting">
PolyBase &amp; pb = func();
</pre>
<p>When the compiler declines to compile this on the basis that a
<tt class="classname">Base</tt> is not a <tt class=
"classname">PolyBase</tt> you stop, think for a moment and come to
the conclusion that while this is true a downcast will be OK
because you have not added any data. So you amend your code to:</p>
<pre class="programlisting">
PolyBase &amp; pb = static_cast&lt;PolyBase&gt;(PolyBase) func();
</pre>
<p><span class="bold"><b>WRONG.</b></span> The chances are very
high that your program is now irredeemably broken. You did (almost
certainly) add data when you derived <tt class=
"classname">PolyBase</tt> from <tt class="classname">Base</tt>.
<tt class="classname">PolyBase</tt> will include a <tt class=
"varname">vftptr</tt>. Worse still, most implementers put this at
the beginning of the class object data. Adding polymorphic
behaviour to a class changes its data layout. Fixing this problem
requires a bit more care. You might try writing an adapter
function:</p>
<pre class="programlisting">
PolyBase pfunc()
{
  return PolyBase(func());
};
</pre>
<p>to construct a <tt class="classname">PolyBase</tt> object that
can be returned by value (the copy constructor will be optimised
away by any respectable compiler). Unfortunately that will not work
as we need a constructor that takes a <tt class=
"classname">Base</tt> by reference (or value) (neither the default
nor copy constructor will do). So we must add:</p>
<pre class="programlisting">
PolyBase(Base const &amp; data): Base(data){}
</pre>
<p>to our class interface. That has a side affect in that it will
suppress the default constructor which we must now make
explicit:</p>
<pre class="programlisting">
PolyBase(){}
</pre>
<p>if we wish to restore that behaviour.</p>
<p>So even our small adaptation to make a class suitable for use as
a polymorphic base class (assuming that there are no
contra-indicators) requires:</p>
<pre class="programlisting">
class PolyBase: public Base
{
public:
  virtual ~PolyBase(){};
  PolyBase(Base const &amp; data)
    :Base(data){}
  // duplication of an explicit 
  // constructors in Base
  // if none then
  // PolyBase(){}
};
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e263" id="d0e263"></a>Adding an
Existing Class to a Hierarchy</h3>
</div>
<p><i class="citetitle">Design Patterns</i> gives an example of
this where you might want to add an existing text object into a
hierarchy of displayable objects. You certainly wish to reuse the
existing code for text but you need to supply an interface that
conforms to that for the displayable hierarchy so that you will get
appropriate polymorphic behaviour. They propose something such
as:</p>
<pre class="programlisting">
class DisplayText :
  public Displayable,
  private Text
{
  // implement Displayable's public 
  // interface
};
</pre>
<p>While I understand the rationale for not using <tt class=
"literal">public</tt> inheritance for <tt class=
"classname">Text</tt> I think that using <tt class=
"literal">private</tt> inheritance is also an error. I think that
if you decide to use the multiple inheritance route, that the
interface should be inherited publicly and the implementation
mechanism should use <tt class="literal">protected</tt>
inheritance. The decision between <tt class="literal">private</tt>
and <tt class="literal">protected</tt> inheritance comes down to
whether inheritance is being used purely for implementation (when
it should be <tt class="literal">private</tt>) or because the
implementation choice might be useful in more derived classes.
There are benefits and costs both ways. So you should think about
it rather than just follow the crowd.</p>
<p>I can see little if any advantage to using <tt class=
"literal">private</tt> inheritance rather than simple composition
or layering. True, you can import functionality with using
declarations, but you can do the same thing with forwarding
functions to make functionality of the data object available in the
protected or public interfaces.</p>
<p>One thought that crossed my mind was that you might want to use
a <tt class="classname">dynamic_cast&lt;&gt;</tt> of a <tt class=
"classname">Displayable</tt> object to determine if it was a
<tt class="classname">Text</tt> one and thereby access the full
public interface of <tt class="classname">Text</tt> if appropriate.
The thing that nags me here (and with the ACCU conference only days
away, I have not time to check all the details) is that I do not
know how <tt class="classname">dynamic_cast&lt;&gt;</tt> treats
<tt class="literal">protected</tt> inheritance, nor do I know how
it treats sub-objects that are non-polymorphic (in other words base
objects that do not support RTTI). Perhaps someone else might
contribute the answers for the next issue. (Some of you are going
to have to start providing something pretty soon because Overload
is being written by far too few people).</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e320" id="d0e320"></a>Subsuming a
Hierarchy</h3>
</div>
<p>As well as adopting a single class into your polymorphic
hierarchy with an appropriate adaptor you might also wish to adopt
a whole hierarchy. In this case inheritance definitely is not what
you want (I assume that you do not want to adopt the classes on a
one by one basis). Straight layering does not help either. You have
two choices, a pointer or a reference. Which you choose is a design
decision. If you are happy for you <tt class=
"classname">DisplayText</tt> object to be specialised to the
specific <tt class="classname">Text</tt> subtype (e.g. <tt class=
"classname">ColouredText</tt>) at construction time then you can
use a reference member. With only the appropriate members listed
something like:</p>
<pre class="programlisting">
class DisplayText: public Displayable
{
  Text &amp; data
public:
  DisplayText(Text &amp; d):data(d){}
};
</pre>
<p>Note that this uses an existing object. You will need to
consider the Observer pattern as well because the display will need
updating if changes are made to the referenced object. If you want
the <tt class="classname">Text</tt> object contained in the
<tt class="classname">DisplayText</tt> one you will need to
investigate creational patterns.</p>
<p>If you want to allow your <tt class="classname">DisplayText</tt>
to change the <tt class="classname">Text</tt> object to a different
one you will need to use a pointer:</p>
<pre class="programlisting">
class DisplayText: public Displayable
{
  Text * data
public:
  DisplayText(Text &amp; d):data(&amp;d){}
};
</pre>
<p>Now you will need to consider what you want to do with
assignment and copy construction. Note that the <tt class=
"classname">DisplayText</tt> object does not own the <tt class=
"classname">Text</tt> object and so you do not need to concern
yourself with problems of deep copying. However your <tt class=
"classname">Text</tt> object might go away so you do need to
implement some variation on the Observer pattern so that the
destruction of your <tt class="classname">Text</tt> results in the
pointer to <tt class="classname">Text</tt> in <tt class=
"classname">DisplayText</tt> being reset to null.</p>
<p>As long as you can get the intercommunication between <tt class=
"classname">Text</tt> objects and <tt class=
"classname">DisplayText</tt> working correctly then the pointer
mechanism is much better than the reference for handling
non-ownership semantics.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e382" id="d0e382"></a>To
Summarise</h3>
</div>
<p>If you want to adopt a single object type into a hierarchy use
either multiple inheritance with <tt class="literal">public</tt>
inheritance of the hierarchy interface and <tt class=
"literal">protected</tt> inheritance of the adoptee</p>
<p>or</p>
<p>single inheritance of the hierarchy interface and layering for
the adoptee.</p>
<p>These mechanisms make the object own the instance of the
adoptee. You do not need to consider the complexity of providing
communication between the adapter and the adoptee but you may need
to consider how, if desirable, you are going to provide access to
the adoptee's <tt class="literal">public</tt> interface.</p>
<p>If you want to adopt a whole hierarchy you must consider whether
the adapter will own the adoptee (either through a pointer or a
reference) or just access a free-standing instance.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e404" id="d0e404"></a>Pluggable
Adapters</h3>
</div>
<p>Let me be entirely honest here; I have no idea what the authors
of <i class="citetitle">Design Patterns</i> mean by these. I find
their text incomprehensible. I would be delighted to read a simple
exposition of this variety of adapter with a good clear example
with reasonably full implementation in code. I understand the
fundamental concept that I might want an adapter that makes minimal
assumptions about the class it is adapting but that is as far as I
can go. I doubt that I am the only one who is confused.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e412" id="d0e412"></a>STL
Adapters</h3>
</div>
<p>There are some interesting examples of adapters in the STL.</p>
<p>We even have examples of adapters that modify behaviour rather
than interface. For example the <tt class=
"classname">reverse_iterator</tt> adapters simply reverse the
direction in which a sequence is traversed. As you might expect,
these are examples of templates that provide the new behaviour
based on the old. The template argument used to instantiate a
<tt class="classname">reverse_iterator</tt> must be an appropriate
type of <tt class="classname">iterator</tt>.</p>
<p>Then we have a wide range of other function adapters such as the
various binders. For example <tt class=
"function">bind2nd&lt;&gt;</tt> is a template function that takes
two parameters. The first is a binary function returning a
<tt class="type">bool</tt> and the second is a value for the second
parameter of that function. Let me give you a simple non-template
example.</p>
<p>Suppose I have a perfectly good function computes the product of
two objects and I need a specific function (with its own distinct
address) that doubles a value. The prototype of the original
function might be:</p>
<pre class="programlisting">
value_t product(value_t, value_t);
</pre>
<p>Now I write:</p>
<pre class="programlisting">
inline value_t times2(value_t val)
{ 
  return product(val, 2);
}
</pre>
<p>Now this kind of adaptation is common (note that default
arguments do not help because I might want to have several
different constant values for the second parameter in different
parts of my program. I could write a special adapter template such
as:</p>
<pre class="programlisting">
template &lt; int i&gt;
inline value_t times_by(value_t)
{
  return product(val, i);
}
</pre>
<p>Now as long as my compiler supports explicit template arguments
for functions I can write something like:</p>
<pre class="programlisting">
value_t val(12.8);
cout &lt;&lt; times_by&lt;3&gt;(val)&lt;&lt; endl;
</pre>
<p>to get three times <tt class="varname">val</tt> sent to
<tt class="classname">cout</tt>.</p>
<p>However this is far from being general enough. Suppose that I
have a function that is something like:</p>
<pre class="programlisting">
template&lt;typename T, typename S&gt; 
  bool has_a_factor(T t, S s);
</pre>
<p>and I want to create a unary function that tests <tt class=
"classname">BigInt</tt> values to see if they are divisible by 37.
The function I want is:</p>
<pre class="programlisting">
bind2nd(has_a_factor&lt;BigInt, int&gt;(), 37);
</pre>
<p>For a single instance this may seem pretty trivial but the STL
is riddled with functions that need some form of test function as a
template parameter. The existence of such template function
adapters makes life much easier (once you get used to using them).
As in my example, the test function itself is often a template
function (STL provides such functions as <tt class=
"function">greater()</tt> ready to plug and play, as long as your
type meets the specified interface requirements)</p>
<p>In addition to a rich collection of function adapters, STL also
includes a variety of class adapters. For example, when we describe
a data structure as a FIFO queue we know exactly what interface we
expect it to present to the user. However there are several
different internal structures (<tt class="classname">deque</tt>,
<tt class="classname">list</tt> etc.) that we might use to
implement the necessary behaviour. As long as we stick to
appropriate standard STL containers we can create queues with the
whole interface generated for us. In deed we can go further if we
wish, by creating our own specialist (either template or plain)
data structures that can plug into the STL queue template. We have
to check exactly what interface elements the STL queue requires of
its template argument but as long as we meet those we have a queue
available on demand.</p>
<p>Much of the power of the STL comes from a wide application of
the adapter concept. It is well worth careful and thoughtful study.
That way you will broaden the range of your programming skills. Do
not waste time re-inventing wheels but do invest time understanding
how wheels work and how to build your own.</p>
<p>Remember that the Amerind (Native American to be PC) never
invented the wheel because wheels do not work well across the range
of snow, ice, pine forest and prairie, runners work much better on
that kind of terrain.</p>
<p>Sorry, but this is as far as I have time to go this time out.
Please write in expanding, correcting etc. on what I have
written.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
