    <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: Substitutability</title>
        <link>https://members.accu.org/index.php/journals/475</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 #39 - Sep 2000 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c165/">39</a>
                    (5)
<br />

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

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

                    -                        <a href="https://members.accu.org/index.php/journals/c165+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;From Mechanism to Method: Substitutability</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 September 2000 17:50:58 +01:00 or Tue, 26 September 2000 17:50:58 +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>If I were to say that C++ is a language with a large number of
features, it is unlikely that I would be in much danger of igniting
a flame war. Where fact gives way to opinion - and sometimes on to
the holiest and heated of wars - is in the recommendation of how to
work with these features. What is their purpose? What concepts do
they express? In short, what methods give sense to the mechanisms,
raising the programmer's view of the language from a shopping list
of features to recipes that marshal features into designs? Sure,
programmers need knowledge of syntax and semantics to make any
headway with the language, but this learning curve pretty soon
peters out to a plateau, with the sheer face of design rising above
it.</p>
<p>Idioms offer a steady and complementary companion route;
patterns that capture an understanding of problem and solution
married together at the level of the language [<a href=
"#Coplien1992">Coplien1992</a>, <a href=
"#Coplien1996">Coplien1996</a>]. They establish a vocabulary for
communicating and formulating design, where &quot;design is the activity
of aligning the structure of the application analysis with the
available structures of the solution domain&quot; [<a href=
"#Coplien1999">Coplien1999</a>].</p>
<p>On the other hand, while practices based on accepted wisdom
generate comfortable habits, generally simplifying day to day
development, this is no reason to be complacent. Occasionally
revisiting old maxims can reveal other useful insights that were
hiding in the shadows [<a href="#Henney1998">Henney1998</a>].</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e38" id="d0e38"></a>'Is a' is not
Enough</h2>
</div>
<p>Attractive as the idea at first seems, the English language does
not offer consistently useful advice for the analysis of problems
and the statement of software structure. Excitement about nouns as
objects and verbs as methods often wears off when the nouning of
verbs and verbing of nouns is recognized as common usage.</p>
<p>So it is with the common good practice recommendation guiding
the use of public inheritance: It should model an is a relationship
rather than <span class="emphasis"><em>ad hoc</em></span> code
reuse. For example, a save-dialog is a dialog box and a list is a
sequence, whereas a bounded list is not an unbounded list and
vice-versa. The view is that reuse (over)driven approaches lead to
the kind of spaghetti inheritance hierarchies that give inheritance
a bad name, and the <span class="emphasis"><em>is a</em></span>
approach constrains inheritance hierarchies to more closely model
expected classifications.</p>
<p>However, like all analogies it has a breaking point, beyond
which rhyme and reason denatures to protracted theological debate
around the coffee machine. For instance, Rex is a dog, and although
his owner might regard him in a class of his own, it is more likely
that developers would view this as an <span class=
"emphasis"><em>instance of</em></span> relationship. Preferring is
<span class="emphasis"><em>a kind of</em></span> to <span class=
"emphasis"><em>is</em></span> a steers us clear of many of the
vagaries of natural language, but not so clear that it clarifies
how state models are inherited or how a virtual function should be
overridden. For example, can a function that in the base class is
guaranteed to accommodate null pointer arguments and never returns
a null pointer be sensibly overridden to accept only non-null
arguments and return null pointers? The linguistic view does not
provide a useful map through such territory.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e62" id="d0e62"></a>Liskov
Substitution Principle</h2>
</div>
<p>The Liskov Substitution Principle (LSP) [<a href=
"#Liskov1987">Liskov1987</a>, <a href=
"#Coplien1992">Coplien1992</a>] is often cited as giving more
detailed guidance on the use of inheritance. It makes a clear
separation between type - described in terms of the behavior of
operations - and class - the realization of the behavior in
programmatic detail - before establishing the criteria for a
subtyping relationship in terms of conformant behavior:</p>
<p>A type hierarchy is composed of subtypes and supertypes. The
intuitive idea of a <span class="emphasis"><em>subtype</em></span>
is one whose objects provide all the behavior of objects of another
type (the <span class="emphasis"><em>supertype</em></span>) plus
something extra. What is wanted here is something like the
following substitution property: If for each object o<sub>1</sub>
of type S there is an object o<sub>2</sub> of type T such that for
all programs P defined in terms of T, the behavior of P is
unchanged when o<sub>1</sub> is substituted for o<sub>2</sub>, then
S is a subtype of T.</p>
<p>So, in answer to the previous question: No, a function cannot
sensibly be overridden to strengthen the requirements on its
arguments and weaken the requirements on its return type. This same
recommendation can be found echoed in Design by Contract [<a href=
"#Meyer1997">Meyer1997</a>].</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e98" id="d0e98"></a>Polymorphic
Polymorphism</h2>
</div>
<p>LSP is normally presented as an inheritance guideline, but
taking a step back we can see that it need not be so narrow: It is
a relationship about types and not implementations, i.e. subtyping
and not subclassing. LSP relies on polymorphism; the concept of
structural relationship, such as public inheritance, need not enter
into it.</p>
<p>C++ developers have inherited (sic) from other OO languages and
literature the notion that polymorphism concerns only inheritance
and virtual functions. Deserving of its name, polymorphism
manifests itself in many forms (see <span class=
"emphasis"><em>Table 1</em></span>). This classification [<a href=
"#Cardelli-1985">Cardelli-1985</a>] gives us a broader and more
liberated view of type relationships. Constraining C++ solely to OO
usage ignores its other strengths and denies its multiparadigm
nature.</p>
<div class="table"><a name="d0e111" id="d0e111"></a>
<table summary="Different kinds of polymorphism" border="1"
cellspacing="0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;thead&gt;
<tr>
<th>Polymorphism</th>
<th>Description</th>
</tr>
&lt;/thead&gt;
&lt;tbody&gt;
<tr>
<td>Inclusion</td>
<td>Conventional OO model of polymorphism, i.e. virtual
functions</td>
</tr>
<tr>
<td>Parametric</td>
<td>Based on provision or deduction of extra type information that
determines the types used in a function, i.e. templates</td>
</tr>
<tr>
<td>Overloading</td>
<td>Based on the use of the same name denoting different functions,
with selection based on the context of use, i.e. argument number
and type</td>
</tr>
<tr>
<td>Coercion</td>
<td>Based on the conversion of an object of one type to an object
of another based on its context of use</td>
</tr>
&lt;/tbody&gt;
</table>
<p class="title c2">Table 1. Different kinds of polymorphism</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e142" id="d0e142"></a>Types of
Substitutability</h2>
</div>
<p>Substitutability is the property that different elements have if
they are grouped - and then treated - in terms of their
commonality; variations that are not relevant to their use are not
a part of this abstraction, or rather they do not dominate
[<a href="#Coplien1999">Coplien1999</a>]. Building on the previous
discussion allows us to think outside the box, giving a broader
view of substitutability grounded in C++'s mechanisms (see
<span class="emphasis"><em>Table 2</em></span>).</p>
<p>The substitutability types are neither perfect peers nor
perfectly hierarchical: They overlap and build on each other.
Nonetheless they offer a useful way to understand and reason about
features. There is a close correspondence between these
substitutability types and the polymorphism categories described in
<span class="emphasis"><em>Table 1</em></span>.</p>
<div class="table"><a name="d0e158" id="d0e158"></a>
<table summary="Different kinds of substitutability in C++."
border="1" cellspacing="0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;thead&gt;
<tr>
<th>Substitutability</th>
<th>Mechanisms</th>
</tr>
&lt;/thead&gt;
&lt;tbody&gt;
<tr>
<td>Conversions</td>
<td>Implicit and explicit conversions</td>
</tr>
<tr>
<td>Overloading</td>
<td>Overloaded functions and operators, often in combination with
conversions</td>
</tr>
<tr>
<td>Derivation</td>
<td>Inheritance</td>
</tr>
<tr>
<td>Mutability</td>
<td>Qualification (typically const) and the use of conversions,
overloading, and derivation</td>
</tr>
<tr>
<td>Genericity</td>
<td>Templates and the use of conversions, overloading, derivation,
and mutability</td>
</tr>
&lt;/tbody&gt;
</table>
<p class="title c2">Table 2. Different kinds of substitutability in
C++.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e194" id=
"d0e194"></a>Conversions</h2>
</div>
<p>Conversions may be implicit or explicit, which places them under
the control of the compiler and the developer, respectively.
Whether a conversion should be implicit or explicit is a mixed
matter of taste, safety and requirement. Widening conversions -
where a conversion is from a specific to a general type - are
always safe and can be implicit without offending sensibilities or
the compiler, e.g. int to double or derived to base. Narrowing
conversions - where a conversion is from a general to a specific
type - are not guaranteed to be safe and should be explicit.</p>
<p>One would hope that it would be required of narrowing
conversions to be explicit, but this is not always the case, e.g.
<tt class="type">double</tt> to <tt class="type">int</tt>. Even
though the compiler does not require it one might argue that taste
does. Where possible, narrowing conversions should be checked, e.g.
the use of <tt class="literal">dynamic_cast</tt> to go from base to
derived.</p>
<p>Developers need to consider the way in which new types
interoperate with one another and with existing types. Particularly
for value types, i.e. for fine-grained objects - such as strings -
that express quantities rather than persistent or strongly
behavioral objects, the use of conversions to and from other types
makes more sense than the use of inheritance relationships.</p>
<p>A single argument constructor is also, by default, a converting
constructor. Where a type be safely, sensibly, and easily used in
place of another type, an implicit conversion into that type either
by converting constructor or a user defined conversion (UDC)
operator may be justified, e.g. use of <tt class="type">const char
*</tt> in many places that a string may be used:</p>
<pre class="programlisting">
class string
{
public:
    string(const char *);
    ...
};

class file
{
public:
    explicit file(const string &amp;);
    ...
};
...
const char *const log_name =
               getenv(&quot;LOGFILENAME&quot;);
file log(log_name ? 
          log_name 
         : &quot;default.log&quot;);
</pre>
<p>Otherwise - and this applies especially to UDCs - single
argument constructors should be declared explicit and UDCs left
unwritten, e.g. a string may not be sensibly used in most of the
places a file object is expected, nor may a string always be used
safely where a <tt class="type">const char *</tt> is expected:</p>
<pre class="programlisting">
class string
{
public:
    ...
    operator const char *() const;
                    // questionable
    ...
};
string operator+(const string &amp;
              , const string &amp;);
...
const string log_suffix = &quot;.log&quot;;
const char *const log_name 
    = getenv(&quot;LOGBASENAME&quot;) + log_suffix;
file log(log_name);
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e226" id=
"d0e226"></a>Overloading</h2>
</div>
<p>Overloading is based on the idea that common name implies common
purpose, and this frees programmers from indulging in their own
name mangling to differentiate similar functions (this is the job
of the compiler). Overloading works closely with - and sometimes
against - conversions. Developers are cautioned to keep any eye
open for any such interference.</p>
<p>Operators provide a predefined set of names and definitions, and
therefore expectations: Overloading <tt class=
"methodname">operator-&gt;</tt> suggests the smart pointer idiom
and overloading <tt class="methodname">operator()</tt> suggests the
function object idiom. Although compilers do not run through your
code checking it for stylistic content (e.g. use of meaningful
variable names, sensible use of overloading, and conformant use of
inheritance) these conventions derive from the language itself to
establish a common frame for working with the language - &quot;when in
doubt, do as the <tt class="type">int</tt>s do&quot; [<a href=
"#Meyers1996">Meyers1996</a>].</p>
<p>Extension through overloading forms is an important part of
operator overloading based substitutability. For instance, a class
that is otherwise closed to change can apparently be extended to
work within a framework, e.g. 'extending' I/O streams to understand
new types.</p>
<p>Some extensions are less transparent, but importantly follow as
much of the base form as possible. An obvious example is the use of
placement <tt class="literal">new</tt> operators which, in spite of
taking additional arguments, have the same purpose and much of the
sameform as the vanilla <tt class="literal">new</tt>. Tagged
overloads, such as <tt class="literal">new(std::nothrow)</tt>,
provide a means of compile time selection that is a compromise
between operators and named functions.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e258" id=
"d0e258"></a>Derivation</h2>
</div>
<p>Substitutability with respect to derivation is perhaps the most
familiar category for programmers coming to C++ with a conventional
OO angle. A public class interface establishes a behavioral
contract the user relies on; derivation through public inheritance
tells the compiler that the types are interchangeable, which only
makes sense if the derived class developer promises to still fulfil
the contract, even if it is extended in some way. Dropping LSP can
lead to some surprising behavior.</p>
<p>In terms of coupling, derivation is also the strongest
relationship one can have in a C++ system: It defines a dependency
that is strongly physical, e.g. with respect to <tt class=
"literal">#include</tt>, as well as one that is strongly logical.
The combined effect can lead to a tsunami-like recompilation of a
whole system rather than a gentle ripple effect whenever the
slightest change is made. Although C++ does not clearly separate
the concepts of subtyping and subclassing in its inheritance
mechanism, it is possible to effect this with interface classes
[<a href="#Carroll-1995">Carroll-1995</a>], i.e. abstract classes
containing only pure virtual functions. This offers a vehicle for
substitutability that is independent of representation issues.
Interestingly this means that as a mechanism, inheritance may be
used either to significantly increase or significantly decrease the
coupling in a system.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e271" id=
"d0e271"></a>Mutability</h2>
</div>
<p>Mutability is concerned with the effects of change. For objects
in C++ this means qualification: <tt class="literal">const</tt> and
<tt class="literal">volatile</tt>... well, <tt class=
"literal">const</tt> if we are being really honest with ourselves.
From this perspective every class has two public interfaces: The
interface for <tt class="literal">const</tt> qualified objects and
the interface for non-<tt class="literal">const</tt> qualified
objects. The <tt class="literal">const</tt> interface is
effectively a subset of the non-<tt class="literal">const</tt>
interface, and therefore a non-<tt class="literal">const</tt>
object may be used wherever a <tt class="literal">const</tt> one is
expected, i.e. the qualified interface may be considered a
supertype of the unqualified one. Note that the subtyping
relationship need not be strict: Overloaded functions differing
only in respect of <tt class="literal">const</tt> or non-<tt class=
"literal">const</tt> will be selected according to the calling
<tt class="literal">const</tt>-ness. In OO terms this can be
considered a form of compile time overriding of the const function
by the non-<tt class="literal">const</tt> variant, typically to
return something more specific:</p>
<pre class="programlisting">
class string
{
public:
    char operator[](size_t) const;
    char &amp;operator[](size_t); 
          // 'overrides' const version
    ...
};
...
const string read_only = ...;
cout &lt;&lt; read_only[0];
string read_write = ...;
cin &gt;&gt; read_write[0];
cout &lt;&lt; read_write[0];
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e317" id=
"d0e317"></a>Genericity</h2>
</div>
<p>Templates offer a route to substitutability that grows out of
the basic concept of overloading. A templated function can be
considered to have a potentially infinite number of overloads all
sharing a common name, purpose and structure, but differing in
their parameter types. A similar view can be extended to template
classes, and from that member templates.</p>
<p>Generic programming, as typified by the part of the standard
library derived from the STL, is based on the compile time
polymorphism of C++ templates, as well as the concepts and
mechanisms of the other substitutability categories.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e324" id=
"d0e324"></a>Conclusion</h2>
</div>
<p>Substitutability provides a useful way to structure the meaning
of a system. It can be recognized as reaching further than a common
place recommendation for inheritance, drawing together many C++
features in a set of practices that make sense of mechanism.</p>
<p>The next few columns will explore the different types of
substitutability in greater detail; looking at language features
and their use in idioms; highlighting the practices that commonly
(or uncommonly) appear in application and library code.</p>
<div class="sidebar">
<p>&quot;From Mechanism to Method: Substitutability&quot;, first appeared in
<i class="citetitle">C++ Report</i> 12(5), May 2000. It is
reprinted here with kind permission of SIGS publishing. Please take
note of their generosity.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e337" id="d0e337"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Cardelli-1985" id=
"Cardelli-1985"></a>
<p class="bibliomixed">[Cardelli-1985] Luca Cardelli and Peter
Wegner, &quot;On Understanding Types, Data Abstraction, and
Polymorphism&quot;, Computing Surveys, 17(4):471-522, December 1985.</p>
</div>
<div class="bibliomixed"><a name="Carroll-1995" id=
"Carroll-1995"></a>
<p class="bibliomixed">[Carroll-1995] Martin D Carroll and Margaret
A Ellis, Designing and Coding Reusable C++, Addison-Wesley,
1995.</p>
</div>
<div class="bibliomixed"><a name="Coplien1992" id=
"Coplien1992"></a>
<p class="bibliomixed">[Coplien1992] James O Coplien, Advanced C++:
Programming Styles and Idioms, Addison-Wesley, 1992.</p>
</div>
<div class="bibliomixed"><a name="Coplien1996" id=
"Coplien1996"></a>
<p class="bibliomixed">[Coplien1996] James O Coplien, Software
Patterns, SIGS, 1996.</p>
</div>
<div class="bibliomixed"><a name="Coplien1999" id=
"Coplien1999"></a>
<p class="bibliomixed">[Coplien1999] James O Coplien,
Multi-Paradigm Design for C++, Addison-Wesley, 1999.</p>
</div>
<div class="bibliomixed"><a name="Henney1998" id="Henney1998"></a>
<p class="bibliomixed">[Henney1998] Kevlin Henney, &quot;Creating Stable
Assignments&quot;, C++ Report 10(6), June 1998.</p>
</div>
<div class="bibliomixed"><a name="Liskov1987" id="Liskov1987"></a>
<p class="bibliomixed">[Liskov1987] Barbara Liskov, &quot;Data
Abstraction and Hierarchy&quot;, OOPSLA '87 Addendum to the Proceedings,
October 1987.</p>
</div>
<div class="bibliomixed"><a name="Meyer1997" id="Meyer1997"></a>
<p class="bibliomixed">[Meyer1997] Bertrand Meyer, Object-Oriented
Software Construction, 2nd edition, Prentice Hall, 1997.</p>
</div>
<div class="bibliomixed"><a name="Meyers1996" id="Meyers1996"></a>
<p class="bibliomixed">[Meyers1996] Scott Meyers, More Effective
C++: 35 New Ways to Improve Your Programs and Designs,
Addison-Wesley, 1996.</p>
</div>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
