    <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 - Good Qualifications</title>
        <link>https://members.accu.org/index.php/articles/371</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 #52 - Dec 2002</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/c191/">52</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+191/">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 - Good Qualifications</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 December 2002 21:57:50 +00:00 or Mon, 02 December 2002 21:57:50 +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>Introduction</h2>
</div>
<div class="blockquote">
<blockquote class="blockquote">
<p>When it is not necessary to change, it is necessary not to
change. Lucius Cary, Viscount Falkland, 1610-1643.</p>
</blockquote>
</div>
<p>Change. In every day life it is seen as something either to
embrace and face or to resist and fear. It is either as good as a
rest or something that leopard spots simply do not do. It is also,
when it comes to matters of state, at the heart of procedural
programming, making it a principle and principal concern for C++
developers: events cause functions to be executed; objects are
created and destroyed; variables are assigned.</p>
<p>But as a path of control flows through our code not everything
is about change. In places the flow is smooth and unchanging, and
importantly so. It is important that things we regard as constants
remain so, giving rise to the oxymoron <span class=
"emphasis"><em>constant variable</em></span>. It is important that
some functions do not change the objects they are called on or
with. It is important that some function results do not allow
subsequent changes.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e31" id="d0e31"></a>Change
Management</h2>
</div>
<p>In C++ the responsibility of documenting and enforcing the
absence of change is given to <tt class="literal">const</tt>, and
that of communicating asynchronous and unpredictable change is
given to <tt class="literal">volatile</tt>, by far the lesser of
the two qualifiers. In combination, the apparently oxymoronic
<tt class="literal">const volatile</tt> leaves many developers
bemused, but makes some sense when applied to references or
pointers that offer read-only semantics to asynchronously changing
values.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e45" id="d0e45"></a>Ringing the
Changes</h2>
</div>
<p>A simple dictionary class, which allows you to look up a string
value based on a unique string key, demonstrates common
applications of <tt class="literal">const</tt> with respect to
member functions, references, and pointers:</p>
<pre class="programlisting">
  class dictionary {
  public:
    bool empty() const;
    size_t size() const;
    const std::string *lookup(
    const std::string &amp;) const;
    void insert(const std::string &amp;,
    const std::string &amp;);
    void erase(const std::string &amp;);
    void clear();
    ...
  private:
    ...
    typedef std::map&lt;std::string,
                     std::string&gt; map;
    map content;
  };
  std::ostream &amp;operator&lt;&lt;(ostream &amp;,
                           const dictionary &amp;);
  std::istream &amp;operator&gt;&gt;(istream &amp;,
                           dictionary &amp;);
  ...
</pre>
<p>With the exception of the <tt class="methodname">lookup</tt>
function, the function names and semantics correspond to those in
the standard library [<a href="#ISO1998">ISO1998</a>]. Being able
to read this interface with respect to mutability helps you
determine some of the expected behavior of the class.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e63" id="d0e63"></a>Don't Change
the Spots</h2>
</div>
<p>In some cases we can allow change behind the scenes with
<tt class="literal">mutable</tt>, supporting discreet change on
data members even under the rule of <tt class="literal">const</tt>.
Sometimes referred to as the <span class=
"emphasis"><em>anticonst</em></span>, <tt class=
"literal">mutable</tt>'s role is to support the occasional
discrepancy between a <tt class="literal">const</tt>-correct class
public interface and its underlying physical implementation. Rather
than modify the interface - and therefore affect the class user -
to reflect optimizations such as caching, mutable allows the
interface to remain stable and implementation details that do not
affect the usage to remain encapsulated.</p>
<p>Let us assume that in using the <tt class=
"classname">dictionary</tt> class we discover that there is a good
chance that we look up a given key many times in a row. We could
try to optimize this by keeping a cache. Preservation of the
class's perceived interface and functional behavior is assisted by
<tt class="literal">mutable</tt>:</p>
<pre class="programlisting">
  class dictionary {
    ...
    mutable map::const_iterator last_lookup;
  };
  const std::string *dictionary::lookup(const std::string &amp;key)const {
    if(last_lookup == content.end() || last_lookup-&gt;first != key)
      last_lookup = content.find(key);
    return last_lookup != content.end() ? &amp;last_lookup-&gt;second : 0;
  }
</pre>
<p><tt class="literal">mutable</tt> has helped bridge any
discrepancy between physical and logical <tt class=
"literal">const</tt>-ness. However, note that this solution is not
appropriate in an environment where dictionary objects are shared
between threads. Between each of these two implementation options
the type perceived by the class user has remained stable.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e100" id=
"d0e100"></a>Substitutability and Mutability</h2>
</div>
<p>What is an object's type? Is it the class from which it is
created? Is it the functions that can be applied to it, whether
global or member? Is it its usage? Is it its capabilities and
behavior? Is it the classification that groups similar objects
together? In truth, type can mean any one of these, depending on
the context. You can see that in some way they are all related - or
at least can be - to one another.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e105" id="d0e105"></a>Of Types and
Classes</h2>
</div>
<p>If we restrict the notion of type to be the declared class of an
object and the functions that work on it, we may have a syntactic
notion of type, but we are short of a model of usage - sure I can
write code against it that compiles, but what am I expecting at
runtime? In the dictionary example, we can see how to write code
that compiles, but what result are we expecting from a call to
<tt class="methodname">dictionary::lookup</tt>? If we say that a
class defines the expected behavior from the member and global
functions that can be applied its instances, we can equate the
syntax and semantics of the class directly with a notion of type
that satisfies most possible definitions of the word.</p>
<p>What about template type parameters? These are constrained by
syntax usage but not by class. That is, after all, the idea of
templates: They are generic and not locked into specific class
hierarchies. In the STL, the compile-time requirements for syntax
usage are supplemented by operational requirements. For instance,
an object that is <span class=
"emphasis"><em>CopyConstructible</em></span> [<a href=
"#ISO1998">ISO1998</a>] satisfies a set of requirements that goes
beyond the simple syntax of a copy constructor, so that <tt class=
"classname">std::list&lt;int&gt;</tt> is <span class=
"emphasis"><em>CopyConstructible</em></span> whereas <tt class=
"classname">std::auto_ptr&lt;int&gt;</tt> is not. These syntactic
and semantic requirements together form an equally valid concept of
type.</p>
<p>What seems to be common across these notions of type is that a
type names and describes a particular model of usage and external
behavior for an object. In the case of a class, the type name
exists explicitly in the source code, the usage is defined by the
functions in its interface (according to the <span class=
"emphasis"><em>Interface Principle</em></span> [<a href=
"#Sutter2000">Sutter2000</a>]), and the behavior is described
outside of the compiled class interface (comments, unit tests,
external documentation, word of mouth, class author's head, etc.).
In the case of a template type parameter, the type name is not
truly in the source code, the usage is defined by expression
syntax, and the behavior is again implied and beyond the code.</p>
<p>So, how do <tt class="literal">const</tt> and <tt class=
"literal">volatile</tt> qualifiers relate to our notion of type?
OK, if we're being practical: How does the <tt class=
"literal">const</tt> qualifier affect our notion of type? When
<tt class="literal">const</tt> is applied to an object, whether
directly on a value declaration or indirectly via a pointer or
reference, it changes our view of that object. To be precise, it
restricts what we can do with it. In other words it affects the
model of usage, and hence the type. For instance, a plain
<tt class="literal">int</tt> supports assignment operations, such
as <tt class="literal">=</tt>, <tt class="literal">+=</tt>, and
<tt class="literal">++</tt>, whereas a <tt class=
"literal">const</tt> int does not. A <tt class=
"classname">std::string</tt> supports modifier functions such as
<tt class="methodname">clear</tt> and <tt class=
"methodname">append</tt>, whereas a <tt class="classname">const
std::string</tt> supports only query functions. Therefore, the
typical class public interface is really two interfaces: The
interface for <tt class="literal">const</tt> qualified objects and
the interface for non-<tt class="literal">const</tt> qualified
objects.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e185" id="d0e185"></a>Of Type
Hierarchies and Class Hierarchies</h2>
</div>
<p>Relating classes together with derivation forms a class
hierarchy. From the perspective of an external user of the class
hierarchy - as opposed to someone implementing or extending it -
only public derivation is of interest. What is the best advice for
forming inheritance relationships? Substitutability or, to be more
precise, the Liskov Substitution Principle (LSP) [<a href=
"#Liskov1987">Liskov1987</a>]:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>A type hierarchy is composed of subtypes and supertypes. The
intuitive idea of a subtype is one whose objects provide all the
behavior of objects of another type (the supertype) plus something
extra. What is wanted here is something like the following
substitution property: If for each object o1 of type S there is an
object o2 of type T such that for all programs P defined in terms
of T, the behavior of P is unchanged when o1 is substituted for o2,
then S is a subtype of T.</p>
</blockquote>
</div>
<p>In a nutshell, class hierarchy should follow type hierarchy.
This recommendation is more detailed than the more common
<span class="emphasis"><em>is-a</em></span> or <span class=
"emphasis"><em>isa- kind-of</em></span> recommendation, which
creates a taxonomy ensuring that each derived class is a kind of
its base class. LSP is more detailed because it considers
explicitly the behavior of the types involved.</p>
<p>Notice that - without actually having it officially stated - the
implicit conversion in C++ from pointers or references from derived
to base underpins an assumption that LSP is followed. The compiler
knows nothing of the expected semantics of your classes, but it
knows in code that where a base instance is expected a derived
instance can be supplied. You drop LSP at your own risk.</p>
<p>There is another assumption that LSP is a recommendation only
for organizing inheritance between classes in OO systems [<a href=
"#Coplien1992">Coplien1992</a>, <a href=
"#Sutter2000">Sutter2000</a>]. Notice that, if you read the
recommendation carefully, there is no mention of classes. LSP is
about relationships between types. Substitutability as defined
applies not only to class hierarchies, but also to other notions of
type based on models of usage [<a href=
"#Henney2000a">Henney2000a</a>]: conversions [<a href=
"#Henney2000b">Henney2000b</a>], overloading [<a href=
"#Henney2000c">Henney2000c</a>], templates (so there is no need for
a generic variant of LSP [<a href="#Sutter2000">Sutter2000</a>]),
and mutability.</p>
<p>We can relate mutability directly to <tt class=
"literal">const</tt> and non-<tt class="literal">const</tt>, and
substitutability to the relationship between them: For a given
class, a non-<tt class="literal">const</tt> object is a subtype of
a <tt class="literal">const</tt> object because it may be used
wherever the <tt class="literal">const</tt> version is expected.
The non-<tt class="literal">const</tt> type also supports the
interface of the <tt class="literal">const</tt> type. Pointer and
reference conversions work in the way that you would expect: To go
from non-<tt class="literal">const</tt> to <tt class=
"literal">const</tt> is implicit, whereas to go the other way,
against the grain, requires an explicit conversion, a <tt class=
"literal">const_cast</tt>. Compare this to the implicit derived to
base conversion with inheritance, and the explicit <tt class=
"literal">static_cast</tt> (or safer <tt class=
"literal">dynamic_cast</tt>) to go the other way.</p>
<p>Returning to the <tt class="classname">dictionary</tt> class, we
can take some artistic and linguistic license to consider it to be
two types with a subtyping relationship between them:</p>
<pre class="programlisting">
  class const dictionary { // not legal C++
  public: // const member functions only
    bool empty() const;
    size_t size() const;
    const std::string *lookup(
    const std::string &amp;) const;
    ...
  };
  // globals taking const dictionary
  // references only
  std::ostream &amp;operator&lt;&lt;(ostream &amp;,
                           const dictionary &amp;);
  ...
  class dictionary : public const dictionary { // not legal C++
  public: // additional non-const
    // member functions
    void insert(const std::string &amp;,
                const std::string &amp;);
    void erase(const std::string &amp;);
    void clear();
    ...
  };
  // additional globals taking non-const
  // dictionary references
  std::istream &amp;operator&gt;&gt;(istream &amp;,
  dictionary &amp;);
  ...
</pre>
<p>From this, it is clear that when we see <tt class=
"classname">const dictionary</tt> in code we are looking at the
<span class="emphasis"><em>as-if</em></span> type represented by
the first fragment, and when we see plain dictionary in code it is
the second fragment, which builds on the first.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e279" id=
"d0e279"></a>Specialization</h2>
</div>
<p>Where there are subtypes there is specialization. Specialization
can be with respect to extension, i.e. the subtype extends the
interface of the supertype with more operations. It can also be
with respect to constraints, i.e. the subtype's operations are more
specific with respect to behaviour or result types.</p>
<p>In a class hierarchy classes typically acquire more operations
the further down the hierarchy you descend. The guarantees of
behavior can also become more specific. For example, if a base
class function guarantees that its pointer result is null or
non-null, an overridden version in a derived class can satisfy
substitutability by never returning null. Conversely, if a base
class function requires that its pointer argument must never be
null, a derived class version can legitimately liberalize this to
also accommodate null. The specialization of result also applies to
return type: Assuming that the return type is a class pointer or
reference, an overridden function can redeclare the return type to
be a derived class pointer or reference.</p>
<p>This much is standard in OO: Runtime polymorphism offers us the
method for such specialization, and <tt class=
"literal">virtual</tt> functions the mechanism. What of <tt class=
"literal">const</tt> and non-<tt class="literal">const</tt>? There
is no concept of runtime polymorphism related to mutability.
However, overloading offers us a compile-time variant of
overriding: We can overload with respect to <tt class=
"literal">const</tt>-ness. In this compile-time view of
polymorphism (the foundation of generic programming in C++)
selection is performed with respect to <tt class=
"literal">const</tt>-ness for member functions on their target
object and functions in general with respect to their
arguments.</p>
<p>Given two member functions of the same name and similar
signature, differentiated only by <tt class=
"literal">const</tt>-ness, the <tt class="literal">const</tt>
version will be the only viable option for <tt class=
"literal">const</tt> access to an object. For non-<tt class=
"literal">const</tt> access, both functions are in theory
available, but the compiler will select the more specific version,
i.e. the non-<tt class="literal">const</tt> one. The most common
reason for such overriding is to specialize the return type, e.g.
<tt class="methodname">operator[]</tt> on strings should allow
scribble access for non-<tt class="literal">const</tt> strings and
read-only access for <tt class="literal">const</tt> strings. In our
<tt class="classname">dictionary</tt> class, a more STL-based
approach to lookup demonstrates this approach:</p>
<pre class="programlisting">
  class dictionary {
  public:
    typedef map::const_iterator const_iterator;
    typedef map::iterator iterator;
    ...
    const_iterator find(const string &amp;) const;
    iterator find(const string &amp;);
    ...
  };
</pre>
<p>Viewing this again in terms of <tt class=
"literal">const</tt>-based type and subtype gives us the following
interfaces:</p>
<pre class="programlisting">
  class const dictionary { // not legal C++
  public:
    const_iterator find(const string &amp;) const;
    ...
  };
  class dictionary : public const dictionary { // not legal C++
  public:
    iterator find(const string &amp;);
    // more specialized 'override'
    ...
  };
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e341" id=
"d0e341"></a>Conclusion</h2>
</div>
<p>In C++, <tt class="literal">const</tt> divides the novice from
the experienced: on one side lies a source of confusion; on the
other a means of clarification. Explicit annotation of modifier
from query functions can benefit a system, and this is a concept
that can be expressed in C++ using type qualifiers. Thus <tt class=
"literal">volatile</tt> and <tt class="literal">const</tt> - as
well as <tt class="literal">mutable</tt> - are unified under the
heading of change, even if the names are not as well chosen as they
might be.</p>
<p>Qualification relates to the notion of type in terms of usage
and behavior, and with it subtyping and all its accumulated
practices and understanding. One valuable property of subtyping is
substitutability. Although it is often clear from the context, we
sometimes need to clarify what kind of substitutability we are
referring to, i.e. substitutability with respect to <span class=
"emphasis"><em>what</em></span>? In the case of <tt class=
"literal">const</tt> it is substitutability with respect to
change.</p>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e366" id="d0e366"></a>References</h2>
</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="Henney2000a" id=
"Henney2000a"></a>
<p class="bibliomixed">[Henney2000a] Kevlin Henney, &quot;From Mechanism
to Method: Substitutability&quot;, C++ Report 12(5), May 2000, also
available from <span class="bibliomisc"><a href=
"http://www.curbralan.com" target=
"_top">http://www.curbralan.com</a></span>.</p>
</div>
<div class="bibliomixed"><a name="Henney2000b" id=
"Henney2000b"></a>
<p class="bibliomixed">[Henney2000b] Kevlin Henney, &quot;From Mechanism
to Method: Valued Conversions&quot;, C++ Report 12(7), May 2000, also
available from <span class="bibliomisc"><a href=
"http://www.curbralan.com" target=
"_top">http://www.curbralan.com</a></span>.</p>
</div>
<div class="bibliomixed"><a name="Henney2000c" id=
"Henney2000c"></a>
<p class="bibliomixed">[Henney2000c] Kevlin Henney, &quot;From Mechanism
to Method: Function Follows Form&quot;, C/C++ Users Journal C++ Experts
Forum, November 2000, <span class="bibliomisc"><a href=
"http://www.cuj.com/experts/1811/henney.html" target=
"_top">http://www.cuj.com/experts/1811/henney.html</a>.</span></p>
</div>
<div class="bibliomixed"><a name="ISO1998" id="ISO1998"></a>
<p class="bibliomixed">[ISO1998] International Standard:
Programming Language - C++, ISO/IEC 14882:1998(E), 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="Sutter2000" id="Sutter2000"></a>
<p class="bibliomixed">[Sutter2000] Herb Sutter, Exceptional
C++.</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>
