    <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  :: Fitting in with multiple frameworks in C++ and Java</title>
        <link>https://members.accu.org/index.php/articles/557</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 #31 - Apr 1999</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/c173/">31</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+173/">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;Fitting in with multiple frameworks in C++ and Java</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 April 1999 17:50:52 +01:00 or Mon, 26 April 1999 17:50:52 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a>Abstract</h2>
</div>
<p>In an application that is using more than one framework there
are occasions when it is desirable for a single object to perform a
role in two (or more) frameworks. We investigate two design
alternatives for combining default implementations provided by the
frameworks with a user defined class that interacts with both.</p>
<p>Outline implementation for these designs are given C++ and Java.
As a result we reach the surprising conclusion that in changing
from one implementation language to the other it is correct to
change between these design alternatives.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e25" id=
"d0e25"></a>Introduction</h2>
</div>
<p>The idea for this article came from a discussion with a
colleague working in Java about the difficulties he was having
trying to combine his extensions to a user interface framework (in
this case Sun's Swing) with the need to integrate these extensions
with a framework that provides an undo facility.</p>
<p>Although I've been dabbling with Java for over two years I still
tend to &quot;think in C++&quot; and translate my C++ approach into Java. At
the design level this is usually an effective way to apply the
experience I've gained over the last decade - it would be
surprising if a design stopped working just because it is expressed
in a different language. (Of course there are some pitfalls to
avoid since C++ supports paradigms that Java doesn't - most notably
generic programming.)</p>
<p>My initial suggestion was based on the way I've tackled similar
problems in C++, by using the &quot;mixin&quot; idiom to interface to both
frameworks and is shown below. Subsequently, I became dissatisfied
with using this approach in Java. Upon examining Java code I'd
written, I realised that in analogous situations I was using a
different approach based on the &quot;adapter pattern&quot;. This seems more
natural in Java and is also illustrated below.</p>
<p>To make the following discussion concrete, let us assume that we
are using two frameworks; one framework delivers the user
interface, whilst the second is an engine for a board game such as
chess. In writing a program we reach the conclusion that we both
want to add a piece to a display in the user interface and to place
it in the board. To achieve this we require a class that that
implements both user interface behaviour (displaying itself) and
application domain behaviour (moving on the board).</p>
<p>Before presenting the code I'd like to make two points:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>in the general case framework interfaces will have a number of
methods, but for the sake of brevity I show only one, and</p>
</li>
<li>
<p>in presenting these approaches in both languages I have adopted
a coding style that emphasises the similarities of design but is
not idiomatic in either language (e.g. it unusual to implement C++
methods in the class body).</p>
</li>
</ol>
</div>
<div class="sidebar">
<p class="title c2">Application Frameworks, Mixins and Adapters</p>
<p>An <i class="firstterm">Application Framework</i> is a library
of interacting classes that provides both the design and a skeleton
implementation of some generic subsystem (for instance a user
interface). By modifying the state of some classes (e.g. adding
buttons) and specialising the behaviour of others (providing a
meaningful response to a button push) the framework is adapted to
the needs of the current program.</p>
<p>A <i class="firstterm">mixin</i> class is one that defines a
protocol required for an operation (such as printing). Inheriting
from a mixin class is a declaration that the protocol is supported
(i.e. that the class is printable) rather than the more common &quot;is
a&quot; relationship. The use of mixins presupposes multiple inheritance
(a document is a file, it is also printable).</p>
<p>An <i class="firstterm">adapter</i> class[<a href=
"#GoF">GoF</a>] is one used to translate between the interface
required by some function (printing again) into that supplied by a
class that doesn't implement that interface directly but does do
something sufficiently similar (provision of display text). An
adapter accepts messages from the function and converts them to
corresponding ones understood by the target class.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e66" id="d0e66"></a>The framework
classes</h2>
</div>
<p>Before looking at the different approaches to implementing our
class we need to provide definitions in C++ and Java of the
framework classes with which we will be working:</p>
<div class="variablelist">
<dl>
<dt><span class="term"><tt class=
"classname">DisplayInterface</tt></span></dt>
<dd>
<p>This defines the protocol used by the display framework to
present an object on the screen.</p>
</dd>
<dt><span class="term"><tt class=
"classname">Display</tt></span></dt>
<dd>
<p>The part of the user interface that we wish to use to display
our piece.</p>
</dd>
<dt><span class="term"><tt class=
"classname">DefaultDisplayInterface</tt></span></dt>
<dd>
<p>Provides a default, do nothing, implementation of the
interface.</p>
</dd>
<dt><span class="term"><tt class=
"classname">PieceInterface</tt></span></dt>
<dd>
<p>This defines the protocol used by the game framework to manage
pieces.</p>
</dd>
<dt><span class="term"><tt class="classname">Board</tt></span></dt>
<dd>
<p>The part of the game framework to which we wish to supply our
piece.</p>
</dd>
<dt><span class="term"><tt class=
"classname">DefaultPieceInterface</tt></span></dt>
<dd>
<p>Provides a default, do nothing, implementation of the
interface.</p>
</dd>
</dl>
</div>
<p>The first listings 1 and 2 provide corresponding C++ and Java
code, so far the differences between the languages are minor and
relate only to their syntax.</p>
<p><span class="bold"><b>Listing 1: Framework classes in
C++</b></span></p>
<pre class="programlisting">
class DrawingSurface;

class DisplayInterface {
public:
  virtual const DisplayInterface&amp; 
  drawOn(DrawingSurface&amp; surface) const = 0;
};

class Display {
public:
  void add(DisplayInterface*);
};

class DefaultDisplayInterface :
  public DisplayInterface {
public:
  virtual const DisplayInterface&amp; 
  drawOn(DrawingSurface&amp;) const
  { return *this; }
};

class PieceInterface {
public:
  virtual PieceInterface&amp; moveTo(
   int file, int rank) = 0;
};

class Board {
public:
  void add(PieceInterface*);
};

class DefaultPieceInterface :
  public PieceInterface {
public:
  virtual PieceInterface&amp; moveTo(int, int) 
  { return *this; }
};
</pre>
<p><span class="bold"><b>Listing 2: Framework classes in
Java</b></span></p>
<pre class="programlisting">
public interface DisplayInterface {
  public DisplayInterface 
  drawOn(java.awt.Graphics surface);
}

public interface Display {
  public void add(DisplayInterface d);
}

public class DefaultDisplayInterface
  implements DisplayInterface {
  public DisplayInterface 
  drawOn(java.awt.Graphics surface)
  {
    return this;
  }
}

public interface PieceInterface {
  public PieceInterface
  moveTo(int file, int rank);
}

public class Board {
  public void add(PieceInterface p);
}

public class DefaultPieceInterface
  implements PieceInterface {
  public PieceInterface
  moveTo(int file, int rank) { return this; }
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e126" id="d0e126"></a>First
approach: using the default implementations as mixins</h2>
</div>
<p>In C++ default implementations from several frameworks can be
used directly: As can be seen from listing 3, if the default
behaviour is all that is required then there is almost nothing to
it! (However, this example will be revisited below under &quot;dealing
with clashes&quot;.)</p>
<p><span class="bold"><b>Listing 3: First approach in
C++</b></span></p>
<pre class="programlisting">
class DisplayPiece : 
  public DefaultPieceInterface, 
  public DefaultDisplayInterface {
};
</pre>
<p>In Java whilst we are able to provide the default
implementations, the rules governing inheritance require that we
inherit from at most one of them. (Java distinguishes &quot;interfaces&quot;
which have no implementation whatsoever from other classes - one
may inherit as many interfaces as one likes and implement the
required methods, but at most one &quot;ordinary&quot; class.)</p>
<p>As usual an extra layer of indirection solves the problem -
listing 4 introduces an extra class whose sole purpose is to
delegate the default behaviour for both interfaces whilst allowing
derived classes to override those that are of interest.</p>
<p><span class="bold"><b>Listing 4: First approach in
Java</b></span></p>
<pre class="programlisting">
// Default implementation for both frameworks
public class AbstractDisplayPieceInterface 
  implements DisplayInterface,
             PieceInterface {

  public DisplayInterface 
  drawOn(java.awt.Graphics surface) {
    d.drawOn(surface);
    return this;
  }

  public PieceInterface
  moveTo(int file, int rank) {
    p.moveTo(file, rank);
    return this;
  }

  final private DisplayInterface d
    = new DefaultDisplayInterface();
  final private PieceInterface p
    = new DefaultPieceInterface();
}

public class DisplayPiece
  extends AbstractDisplayPieceInterface {
};
</pre>
<p>Although this code proves that default interfaces can be mixed
in Java I'm far from convinced that this is a good approach! There
is a serious potential &quot;gotcha&quot; - when there are several methods
defined in the interface it is possible for one of the default
method implementations to be defined in terms of another - the
approach shown doesn't work when only the latter method is
overridden.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e147" id="d0e147"></a>Second
approach: deriving adapters from the default implementations</h2>
</div>
<p>What I came to realised was that Java's &quot;anonymous local
classes&quot; provide a very elegant alternative based on the adapter
pattern described by the &quot;Gang of Four&quot;[<a href="#GoF">GoF</a>]
(and that I was already using it on a regular basis).</p>
<p>The use of adapters frees the <tt class=
"classname">DisplayPiece</tt> class from the need to implement the
interfaces required by the framework directly. Also an adapter for
one framework doesn't need to implement any of the functionality
required by the other, so multiple inheritance isn't an issue.</p>
<p>Listing 5 shows an implementation using this approach - the
<tt class="classname">DisplayPiece</tt> class implements
functionality corresponding to the methods we wish to adapt and two
fragments of &quot;client code&quot; that create suitable adapters for the
two frameworks.</p>
<p><span class="bold"><b>Listing 5: Second approach in
Java</b></span></p>
<pre class="programlisting">
public class DisplayPiece {
  private void
  myDrawOn(java.awt.Graphics surface) {}
  private void
  myMoveTo(int file, int rank) {}
}

// &quot;client code&quot; fragment #1
  void addToDisplay(Display d,
                    final DisplayPiece p) {
    d.add( new DefaultDisplayInterface() {
        public DisplayInterface 
        drawOn(java.awt.Graphics surface) {
          p.myDrawOn(surface);
          return this;
        } } );
  }

// &quot;client code&quot; fragment #2
  void addToBoard(Board g,
                  final DisplayPiece p) {
    g.add( new DefaultPieceInterface() {
        public PieceInterface
        moveTo(int file, int rank) {
          p.myMoveTo(file, rank);
          return this;
        } } );
  }
</pre>
<p>The reason for presenting the Java code first in this approach
is that in C++ we still have a major design decision to make -
something needs to own the adapter classes and to control their
lifetimes - they have to be deleted when they are no longer used.
(In Java the &quot;virtual machine&quot; reclaims memory that is no longer in
use, C++ requires the programmer to know when this happens and to
release it herself.)</p>
<p>For the sake of simplicity in listing 6 I've chosen to embed the
adapters as nested classes within the <tt class=
"classname">DisplayPiece</tt> class. This ensures that they will be
deleted with it. Another valid solution is to embed them into a
separate controlling class.</p>
<p><span class="bold"><b>Listing 6: Second approach in
C++</b></span></p>
<pre class="programlisting">
class DisplayPiece {
public:
  DisplayPiece() : pia(*this), uia(*this) { }
  operator PieceInterface&amp;() { return pia; }
  operator DisplayInterface&amp;() { return uia; }
  void myMoveTo(int, int)
  { /* &hellip; &hellip; */ }
  void myDrawOn(DrawingSurface&amp;) const
  { /* &hellip; &hellip; */ }

private:
  class PieceInterfaceAdapter :
    public DefaultPieceInterface {
  public:
    PieceInterfaceAdapter(
      DisplayPiece&amp; adaptee) 
    : body(adaptee) { }
    PieceInterface&amp; moveTo(int file, int rank)
    { 
      body.myMoveTo(file, rank); 
      return *this;
    }
    DisplayPiece&amp; body;
  private:
    PieceInterfaceAdapter(
      const PieceInterfaceAdapter&amp;);
    PieceInterfaceAdapter&amp; operator=(
      const PieceInterfaceAdapter&amp;);
  } pia;

  class DisplayInterfaceAdapter :
    public DefaultDisplayInterface {
  public:
    DisplayInterfaceAdapter(
      DisplayPiece&amp; adaptee)
    : body(adaptee) { }
    const DisplayInterface&amp; 
    drawOn(DrawingSurface&amp; s) const
    { 
      body.myDrawOn(s); 
      return *this;
    }
    DisplayPiece&amp; body;
  private:
    DisplayInterfaceAdapter(
      const DisplayInterfaceAdapter&amp;);
    DisplayInterfaceAdapter&amp; operator=(
      const DisplayInterfaceAdapter&amp;);
  } uia;

  DisplayPiece(const DisplayPiece&amp;);
  DisplayPiece&amp; operator=(
    const DisplayPiece&amp;);
};
</pre>
<p>In the first approach we found the Java code to be more
elaborate than the C++, now that situation has been reversed. By
making the C++ framework more complex and providing a template
adapter class we could perhaps reduce the complexity of the client
code a little, but the requirement for explicit memory management
remains.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e184" id="d0e184"></a>Dealing with
clashes</h2>
</div>
<p>Returning to the first approach, there is a possibility that
both interfaces may have a method with the same signature. For the
sake of argument suppose that both interfaces declare a method
<tt class="methodname">void clash()</tt>. If we were to override
this method in our <tt class="classname">DisplayPiece</tt> class
then we would have difficulty determining through which interface
we were being invoked.</p>
<p>In C++ this issue can be resolved by adding a pair of
intermediate classes into the hierarchy that effectively rename the
message so that we can determine its origin. Listing 7 shows the
way.</p>
<p><span class="bold"><b>Listing 7: Dealing with clashes in
C++</b></span></p>
<pre class="programlisting">
class IntermediateDisplay :
  public DefaultDisplayInterface {
public:
 // DO NOT OVERRIDE clash() -
 // override displayClash() instead
 virtual void clash() { displayClash(); }
 virtual void displayClash() { 
  DefaultDisplayInterface::clash();
 }
};

class IntermediatePiece :
 public DefaultPieceInterface {
public:
 // DO NOT OVERRIDE clash() -
 // override pieceClash() instead
 virtual void clash() { pieceClash(); }

 virtual void pieceClash() {  
  DefaultPieceInterface::clash();
 }
};

class DisplayPiece : 
 public IntermediatePiece, 
 public IntermediateDisplay {
};
</pre>
<p>As this technique relies on multiple inheritance there is no
corresponding solution in the Java case.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e204" id="d0e204"></a>Final
thoughts</h2>
</div>
<p>In a very real sense we have been looking at two different
formulations of a single idea - an object that can interact with
both the display and the board. What is surprising is that the
choice of implementation language has such a dramatic effect on the
ease with which each approach can be expressed. It could be argued
that the correct translation of listing 3 is not listing 4 (which
is not idiomatic Java), but listing 5 (which is).</p>
<p>The idea that an &quot;adapter&quot; is the correct translation of a
&quot;mixin&quot; seems strange at first but Kevlin Henney [<a href=
"#Henney">Henney</a>] has previously observed similar relationship
between &quot;iteration&quot; and &quot;enumeration&quot; when moving between
languages. This change of form as a result of translation isn't
just a characteristic of computer languages - Douglas Hofstadter
[<a href="#Hofstadter">Hofstadter</a>] dedicates a substantial
volume to similar interactions between the ideas being expressed
and the forms of expression in different natural languages.</p>
<p>Why does changing the implementation language change the way in
which the problem is solved?</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>The mixin approach works well in C++ because it removes the
problem of object lifetimes that occurs in the adapter approach. In
addition, the more flexible C++ inheritance model allows default
behaviours to be combined and the occasional problem of methods
clashing to be resolved.</p>
</li>
<li>
<p>The adapter approach works well in Java both because of the
lightweight syntax for declaring anonymous local classes and
because the JVM, not the programmer has responsibility for
controlling object lifetimes.</p>
</li>
</ol>
</div>
<p>Mixins and adapters are both idioms I've used before, but I
hadn't previously considered the possibility of a relationship
between them. I see now that they are very close and solve related
problems. The choice between them may depend on the fine detail of
the problem at hand.</p>
<p>For those that wish to draw conclusions about the superiority of
one language or the other I've shown that both choices are always
available in C++, whilst the mixin approach may sometimes be
problematic in Java. On the other hand the adapter approach is
sufficient in Java and very flexible.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e230" id="d0e230"></a>References</h2>
</div>
<div class="bibliomixed"><a name="GoF" id="GoF"></a>
<p class="bibliomixed">[GoF] ISBN 0-201-63361-2 &quot;<span class=
"citetitle"><i class="citetitle">Design Patterns</i></span>&quot;,
Gamma, Helm, Johnson, Vlissides, Addison-Wesley 1997</p>
</div>
<div class="bibliomixed"><a name="Henney" id="Henney"></a>
<p class="bibliomixed">[Henney] &quot;<span class="citetitle"><i class=
"citetitle">Idioms - Breaking the Language Barrier</i></span>&quot;,
Kevlin Henney, European C and C++ Users Conference 1998</p>
</div>
<div class="bibliomixed"><a name="Hofstadter" id="Hofstadter"></a>
<p class="bibliomixed">[Hofstadter] ISBN 0 7475 3349 0
&quot;<span class="citetitle"><i class="citetitle">Le Ton beau de
Marot</i></span>&quot; Douglas Hofstadter, Bloomsbury 1997</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
