    <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  :: Student Code Critique Competition</title>
        <link>https://members.accu.org/index.php/articles/1164</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">Student Code Critiques from CVu journal. + CVu Journal Vol 14, #2 - Apr 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/c184/">Journal Columns</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c183/">Code Critique</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/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c115/">142</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c183+115/">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;Student Code Critique Competition</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 05 April 2002 13:15:51 +01:00 or Fri, 05 April 2002 13:15:51 +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><span class="bold"><b>Prizes provided by Blackwells Bookshops
&amp; Addison-Wesley</b></span></p>
<p>Please note that participation in this competition is open to
all members, and is not restricted to students. The title reflects
the fact that the code used is normally provided by a student as
part of their course work.</p>
<p>Note that this item is part of the Dialogue section of C Vu
which is intended to designate it as an item where reader
interaction is particularly important. Readers' comments and
criticisms of published entries are always welcome.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e27" id="d0e27"></a>Student Code
Critique 14: The Entries</h2>
</div>
<p>Things go in cycles. I had three competition submissions this
time round but one completely forgot to include their name. It is
important that your name is somewhere in the actual submission
because it other wise gets lost when I detach the attachment. As I
have mentioned this before I am going to be tough and disqualify
that entry (don't take it too hard, it just makes it easier for me
to select a winner.) Gary Joy gave it a good shot but on balance I
think Chris Main comes out ahead. Perhaps Chris would contact me to
discuss his prize.</p>
<p>I also include a submission from our old friend who writes under
the pseudonym of <span class="emphasis"><em>The
Harpist</em></span>.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e37" id="d0e37"></a>The original
code</h3>
</div>
<p>I always try to fit this code in, but doing so this time has
unpleasant consequences like what else should I drop to make the
page count. So this time you will either have to dig out your last
issue or visit the ACCU web site.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e42" id="d0e42"></a>Critique from Gary
Joy <tt class="email">&lt;<a href=
"mailto:garyj0y@yahoo.co.uk">garyj0y@yahoo.co.uk</a>&gt;</tt></h3>
</div>
<p>Hello, I am a relatively new (6 months now&hellip;) C++
programmer and I thought I'd have a go at the critique competition.
I am not especially confident so this should be a good learning
process for me; to that end feel free to replace 'I like
to&hellip;' with 'I think it's good practice but I'm worried that
I'm wrong&hellip;' in my comments. ;-)</p>
<p>I appreciate that limitations dictate what you can print so I
will refrain from 'comments' comments etc. except to say that the
code really belongs in five files: <tt class=
"filename">Hand.h</tt>, <tt class="filename">Hand.cpp</tt>,
<tt class="filename">Card.h</tt>, <tt class=
"filename">Card.cpp</tt> and <tt class=
"filename">Main.cpp</tt>.</p>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e66" id="d0e66"></a>Card class</h4>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3><a name="d0e69" id="d0e69"></a>To make it
work:</h5>
</div>
<p>The closing brace for the constructor is missing.</p>
<p>The local variable <tt class="varname">face_value</tt> used in
the constructor is not defined.</p>
<p>I am using VS 6 and I don't need <tt class="literal">std::</tt>
for <tt class="function">tolower()</tt> and <tt class=
"function">strchr()</tt>. Reading the documentation it states that
<tt class="literal">#include &lt;cstring&gt;</tt> should make it
available in the <tt class="literal">std::</tt> namespace. I await
the next issue...</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3><a name="d0e96" id="d0e96"></a>To make it
better:</h5>
</div>
<p>Keep the variable names in <tt class="filename">.h</tt> and
<tt class="filename">.cpp</tt> files consistent. (i.e. constructor
argument is <i class="parameter"><tt>face_value</tt></i> versus
<i class="parameter"><tt>face_val</tt></i> - this is probably why
<i class="parameter"><tt>face_value</tt></i> was not defined.)</p>
<p><tt class="methodname">operator()</tt> is defined but never used
for <tt class="classname">Card</tt>. (It could be used in
<tt class="methodname">calculate_total()</tt>.)</p>
</div>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e126" id="d0e126"></a>Hand class</h4>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3><a name="d0e129" id="d0e129"></a>To make it
work:</h5>
</div>
<p><tt class="literal">#include Card.h</tt> is missing quotes (&quot;&quot;)
around the filename.</p>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3><a name="d0e136" id="d0e136"></a>To make it
better:</h5>
</div>
<p>// No need for 'tors' - I like to have them anyway.</p>
<p class="c2"><span class="remark">FG: Actually there are good
reasons for not defining 'tors' if the compiler will do the right
thing. It allows the compiler more scope for
optimization.</span></p>
<p>The <tt class="methodname">add_card</tt> argument is not named -
I know that you do not need to include a name but I like to.</p>
<p class="c2"><span class="remark">FG: But why? In this case what
parameter name would add to the reader's understanding of the
prototype? My preference is for using names where they add
understanding but not otherwise.</span></p>
<p><tt class="methodname">calculate_total</tt> and <tt class=
"methodname">show_total</tt> could be <tt class=
"literal">const</tt> functions.</p>
<p class="c2"><span class="remark">FG: I would be stronger, and say
they should be. It is almost invariably a design error for a
non-mutating member function not to be a <tt class=
"literal">const</tt> member.</span></p>
<p>Keep names consistent - call the <tt class=
"classname">ostream</tt> <tt class="methodname">bjout</tt> instead
of <tt class="methodname">strm</tt> in the <tt class=
"methodname">show_total</tt> prototype. <tt class=
"methodname">show_total</tt> doesn't need to return anything.</p>
<p class="c2"><span class="remark">FG: That is true but many people
like to use this form because it makes it easier to use the
function to implement <tt class=
"methodname">operator&lt;&lt;()</tt>.</span></p>
<p>I like to initialise variables: <tt class="varname">valid</tt>
and <tt class="varname">face_value</tt>. <tt class=
"methodname">input_hand</tt> could be split into two functions to
simplify it.</p>
</div>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e202" id="d0e202"></a>main()</h4>
</div>
<div class="sect4" lang="en">
<div class="titlepage">
<h3><a name="d0e205" id="d0e205"></a>To make it
better:</h5>
</div>
<p>Initialise <tt class="varname">answer</tt>.</p>
</div>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e213" id="d0e213"></a>General
Comments</h4>
</div>
<p>There are no destructors. Even if they are empty I like to have
a destructor for every class.</p>
<p class="c2"><span class="remark">FG: See my earlier comment.
Indeed, an insistence on providing a destructor coupled with the
frequent insistence that functions are not defined in the class
interface can lead to awkward code elsewhere.</span></p>
<p>After the <tt class="literal">#include</tt> of parts of MFC add
a comment to indicate why... (E.g. <tt class="literal">#include
&lt;cstring&gt; // (strchr)</tt>) This is more of a suggestion than
a critique.</p>
<p class="c2"><span class="remark">FG:If it were MFC I think I
might but that is part of The C++ Standard Library and I would
expect programmers to be fairly familiar with that.</span></p>
<p>Don't use <tt class="literal">using namespace std</tt> (at the
very least not in headers). Not only does it save including lots of
stuff that you don't need but it also makes it clear what you are
using from the <tt class="literal">std</tt> namespace. Either use
using <tt class="classname">std::cout;</tt> or qualify within the
code (<tt class="classname">std::cout</tt>).</p>
<p class="c2"><span class="remark">FG: Definitely not in global
space in a header. However I am happy when the directive is inside
a user namespace or an implementation file.</span></p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e249" id="d0e249"></a>Being Picky
:-)</h4>
</div>
<p>There is no validation of the input:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>It is should not be possible to have five aces. (I guess they
use several decks at casinos...)</p>
</li>
<li>
<p>The input stream is not managed, i.e. if I type in
&quot;2kay3ttay5a2345n&quot;, I will play three games in the blink of an
eye.</p>
</li>
</ol>
</div>
<p>I think that the OOP design is reasonable - the code could be
readily re-used as part of another game - e.g. by deriving a class
from <tt class="classname">Hand</tt>, (<tt class=
"classname">Poker_Hand</tt>) we could play poker instead. (With
only a tiny change to the <tt class="function">main()</tt>
function).</p>
<p class="c2"><span class="remark">FG: I would disagree because
derivation should only be applied to things that were designed with
that in mind. The lack of a virtual destructor strongly suggests
that the writer had no intention that his class should be a base
class.</span></p>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e275" id="d0e275"></a>From Chris Main
<tt class="email">&lt;<a href=
"mailto:chris@chrismain.uklinux.net">chris@chrismain.uklinux.net</a>&gt;</tt></h3>
</div>
<p>My first comment on the code is the one made by Catriona
O'Connell in the previous Critique: it exhibits &quot;the intertwining
of user input and calculations&quot;.</p>
<p>In class <tt class="classname">Hand</tt> there are four public
member functions. Two relate to input and output (<tt class=
"methodname">input_hand()</tt>, <tt class=
"methodname">show_total()</tt>) and two to the calculation
(<tt class="methodname">add_card()</tt>, <tt class=
"methodname">calculate_total()</tt>). This distinction is clarified
by the observation that the latter two are only ever called by the
former two, and not by any client of <tt class=
"classname">Hand</tt>.</p>
<p>I suggest removing <tt class="methodname">input_hand()</tt> and
<tt class="methodname">show_total()</tt> from <tt class=
"classname">Hand</tt> and making them standalone functions,
declared in a separate header file (named <tt class=
"filename">handIO.h</tt> say). They would need additional
parameters, <i class="parameter"><tt>Hand&amp;</tt></i> and
<i class="parameter"><tt>Hand const&amp;</tt></i> respectively. I
would remove the existing stream parameters as they are promising
more than they are delivering. The implementation of the functions
is really only appropriate for <tt class="classname">cout</tt> and
<tt class="classname">cin</tt>.</p>
<p>I think there is scope for improving the function names.
<tt class="methodname">add_card()</tt> could become simply
<tt class="methodname">add()</tt> since I think <tt class=
"literal">hand.add(aCard)</tt> reads better than <tt class=
"literal">hand.add_card(aCard)</tt>. Likewise <tt class=
"methodname">input_hand()</tt> could be replaced by <tt class=
"methodname">input()</tt>. I would change <tt class=
"methodname">calculate_total()</tt> to <tt class=
"methodname">total()</tt> since the function is returning the value
of an attribute of the class - whether we perform the calculation
of that value in that particular function is an implementation
detail. This detail is of no interest to clients, so it ought to be
concealed from them. [I also think <tt class=
"methodname">value()</tt> would be a more exact name than
<tt class="methodname">total()</tt>, but that is a rather more
subjective opinion.]</p>
<p><tt class="classname">Hand</tt> encapsulates a vector of
<tt class="classname">Card</tt>s, which sounds good. However when
we inspect class Card more closely we discover that it only
encapsulates a card value without encapsulating the card's name.
This is an important distinction in this application because
<tt class="methodname">Hand::calculate_total()</tt> sometimes needs
to know whether there is an ace in the hand. It does this in the
submitted code by making an assumption about the value assigned to
an ace by <tt class="classname">Card</tt>. The algorithm for
<tt class="methodname">calculate_total()</tt> additionally depends
upon the value assigned to an ace because that determines whether
it should increment or decrement by 10 when adjusting the value of
the hand. For these two reasons, the value assigned to an ace
cannot be encapsulated internally within <tt class=
"classname">Card</tt>.</p>
<p>We could re-design so that the ace value is visible to both
<tt class="classname">Card</tt> and <tt class=
"classname">Hand</tt>, but I think a cleaner design results from
encapsulating that value internally within <tt class=
"classname">Hand</tt> (cleaner in the sense that there are fewer
interdependencies). In this scheme, <tt class="classname">Card</tt>
would encapsulate just the name of a card. An obvious choice would
be to make it an <tt class="literal">enum</tt>. This may be good
enough, but it must be borne in mind that in C/C++, unlike
Pascal/Ada, an <tt class="literal">enum</tt> value is a thinly
disguised integer which can be used in arithmetic operations
without explicit casting. In the light of the exchange between Paul
Whitehead and Francis Glassborow (<i class="citetitle">C Vu
13.6</i>, Dec. 2001) on ADTs, we may prefer to make it a class
exporting static <tt class="literal">const</tt> values, with
constructors disabled so that no other valid values can be created.
(A default constructor creating an invalid value should be made
available so that the class can be used with STL containers).</p>
<p>Again, I would separate the user input aspects of <tt class=
"classname">Card</tt> into a standalone function <tt class=
"function">input(Card&amp;)</tt>. How should we map a character
input by a user to a <tt class="classname">Card</tt>? The answer is
in the question: a map. I really liked Colin Hersom's proposal to
do this in the previous Critique, and I was only sorry that he
didn't carry it through fully. His comment &quot;See how it would have
been neater if we used a class?&quot; would more accurately have been
stated &quot;See how messy it is without a class?&quot; If we make the
<tt class="literal">map&lt;char, Card&gt;</tt> a private member
variable of a wrapper class it can be populated in the constructor
of the wrapper class. Then within <tt class=
"function">input(Card&amp;)</tt> all we need to do is declare a
static local variable of the wrapper class.</p>
<p>The submitted code throws an exception when an invalid character
is entered. I consider this unduly aggressive; miss-typing by a
user should be expected by the program rather than treated as an
exceptional occurrence. Instead the map-wrapper class could have a
member function <tt class="function">lookup(char, Card&amp;)</tt>
returning a bool to indicate whether it can map the character to a
<tt class="classname">Card</tt>.</p>
<p>Turning then to the implementation of <tt class=
"classname">Hand</tt>, what container should we use? What should it
contain? Do we want to make it a pointer so that we can use the
pImpl/CheshireCat/Handle-Body/Bridge idiom/pattern (delete
according to taste)? There are a number of valid options, depending
upon the exact use we wish to make of our <tt class=
"classname">Hand</tt> class. We could keep these options open by
making <tt class="classname">Hand</tt> a template, to be
instantiated with the container implementation class. To describe
how to do this is beyond the scope of a code critique; I will try
to write a separate article.</p>
<p>If, as I have argued, <tt class="classname">Card</tt>
encapsulates a name rather than a value a map is likely to be a
more suitable container than a <tt class="classname">vector</tt>.
We sometimes need to find aces in the hand, and <tt class=
"function">find</tt> is optimised for maps (or should that be maps
are optimised for find?). [For the paranoid, and it probably pays
to be paranoid in relation to gambling card games, representing
Card as a name rather than a value gives us the opportunity to
check for five of the same card in a hand.]</p>
<p>How should <tt class="function">calculate_total()</tt>
accumulate the value of the hand? The answer is in the question (if
we <tt class="literal">#include &lt;numeric&gt;</tt>):</p>
<pre class="programlisting">
unsigned int value =  std::accumulate(cards.begin(), cards.end(),
      0, AccumulateCardValue(cardValues()));
</pre>
<p>What is <tt class="function">cardValues()</tt>? A function that
returns a reference to another Colin Hersom style lookup map,
wrapped in a class and declared as a <tt class=
"literal">static</tt> local variable within the function. The case
for such a map rather than a <tt class=
"literal">switch</tt>-statement is stronger here: in the <tt class=
"literal">switch</tt>-statement submitted a calculation is
performed every time a numerical value is looked up:</p>
<pre class="programlisting">
numerical_value = face_val - '0';
</pre>
<p>The syntactic tidiness of the switch fall through conceals the
potential for inferior performance. Note that the common (in my
experience) practice of declaring <tt class=
"methodname">cardValues()</tt> as a private member function, in
this case a <tt class="literal">static</tt> one, clutters the
header file unnecessarily. Instead it can be declared within an
unnamed namespace in the implementation file (equivalent to a
<tt class="literal">static</tt> function in C).</p>
<p>What is <tt class="function">AccumulateCardValue</tt>? A
function object class more succinctly listed than described:</p>
<pre class="programlisting">
class AccumulateCardValue {
  public:
    AccumulateCardValue(
            const CardValues&amp; cardValues)
      : values(cardValues){}
    unsigned int operator()(
          unsigned int accumulatedValue,
          Cards::value_type const&amp; card) {
// Exact implementation depends upon
// Cards::value_type
// In pseudo code:
// card found = values.lookup(card name, card
// value) if not card found then throw
// exception return accumulatedValue + 
// (card value * number of cards)
    }
  private:
    const CardValues&amp; values;
};
</pre>
<p>In this case it is an unexpected occurrence for the lookup to
fail, so it is legitimate to throw an exception. I would simply
derive my exception class from <tt class=
"exceptionname">std::exception</tt> rather than build my own as
done in the submitted code.</p>
<p>A final observation on <tt class=
"function">calculate_total()</tt>: there is no need to check for
aces during the accumulation loop, and indeed no need to check for
them unless the hand value thus accumulated is less than 12.</p>
<p>I suspect some readers will remain uneasy about my proposal to
strip the value attribute from the <tt class="classname">Card</tt>
class. My solution is fine in the case that we only ever want to
calculate the value of a hand once, when the hand is complete.
Well, maybe that is all our application requires. It is, though,
easy to imagine there might be a requirement to show the value of
the hand after each card is added. In that case it is obviously
sensible to cache the value of each card the first time it is
looked up. This can easily be achieved within my design by changing
the class of the objects held by the container, adding a value
attribute to those objects. This value attribute could be
initialised when the card is added to the hand (here we see the
value of encapsulating card values in the <tt class=
"function">cardValues()</tt> function), and the implementation of
<tt class="function">AccumulateCardValue</tt> is made simpler
correspondingly. At this stage you may realise the usefulness of
making the container implementation class a template parameter, and
if you've used the pImpl idiom your clients won't even be affected
by such a modification.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e517" id="d0e517"></a>From Anon2</h3>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e520" id="d0e520"></a>Card.h</h4>
</div>
<p>I would first of all replace the class name <tt class=
"classname">Card</tt> with <tt class="classname">CardValue</tt>, as
strictly speaking this is the entity being modelled, rather than an
actual card. The original program does not deal with actual cards
(which would be specified with the two parameters of suit and
denomination). It only specifies a means of identifying a card's
denomination in order to calculate the card's value in the game. In
other card games the suit may come into it, and a <tt class=
"classname">Card</tt> class could consist of an enumeration
<tt class="literal">enum SUIT{HEARTS, DIAMOND, CLUBS, SPADES};</tt>
and two member variables - <tt class="varname">Suit</tt>, of type
<tt class="type">SUIT</tt>, and <tt class=
"classname">Denomination</tt>, an <tt class="varname">int</tt>
denoting 1 (Ace) to 13 (King).</p>
<p class="c2"><span class="remark">FG: I think those all upper case
spellings are a defect. They result in making code unnecessarily
fragile in the presence of the pre-processor and they make code
harder to read. And why is the suit an enum but not the
denomination?.</span></p>
<p>The constructor of <tt class="classname">Card</tt> does not need
to be made <tt class="literal">explicit</tt>. A constructor of a
class <tt class="classname">C</tt> able to take a single parameter
of a type TYPE is made explicit to prevent the compiler using it to
perform an automatic type conversion from <tt class=
"type">TYPE</tt> to <tt class="classname">C</tt> in a function call
or in an expression. In such a case a <tt class="classname">C</tt>
or <tt class="type">C &amp;</tt> is expected, but a <tt class=
"type">TYPE</tt> is passed. The compiler creates code that invokes
that constructor to produce an instance of the expected class
<tt class="classname">C</tt>. An example from the STL is the
<tt class="classname">vector</tt> class, which has a constructor
taking as a first parameter an integral value, followed by two
parameters with default values, the first one of which is an
instance of the vector's parameterised type <tt class=
"type">T</tt>, as created by invoking its default constructor
<tt class="methodname">T()</tt>. Calling this constructor with a
value <i class="parameter"><tt>N</tt></i> as a single parameter
results in a vector of <i class="parameter"><tt>N</tt></i> elements
of the object <tt class="methodname">T()</tt>. If <tt class=
"type">T</tt> were the type string this would give a vector of
<i class="parameter"><tt>N</tt></i> null strings, or if <tt class=
"type">T</tt> was an <tt class="type">int</tt> it would give a
vector of <i class="parameter"><tt>N</tt></i> zeros, and so on. The
question is does it make sense or does it cause any confusion to
create such an object when the user specifies an integer value
<i class="parameter"><tt>N</tt></i> where a <tt class=
"classname">vector&lt;T&gt;</tt> is expected. As an example suppose
we had a function <tt class="function">void output(const
vector&lt;T&gt; &amp; v)</tt> which just outputted on separate
lines the elements in the vector v. If <tt class="literal">T =
string</tt> or <tt class="literal">T = int</tt> the user may call
<tt class="methodname">output(5)</tt>, expecting the number 5 to be
treated as a single element vector, and so get &quot;5&quot; appearing on a
line by itself. However what they would get is 5 blank lines if
<tt class="literal">T = string</tt>, and 5 zeros on separate lines
if <tt class="literal">T = int</tt>. To avoid this confusing
situation the STL vector class declares the above constructor to be
<tt class="literal">explicit</tt>. Then <tt class=
"methodname">output(5)</tt> cannot compile (on VC++ 6.0 the error
reports that &quot;no constructor could take the source type&quot;).</p>
<p>There is no comparable ambiguity in the case of the <tt class=
"classname">Card</tt> class, a <tt class="type">char</tt> can
always be substituted for a <tt class="classname">Card</tt> object
without being counter-intuitive as in the case of the <tt class=
"classname">vector</tt> class above. Therefore I would not make the
constructor <tt class="literal">explicit</tt>. (Note of course not
all <tt class="type">char</tt>s can be successful in becoming a
<tt class="classname">Card</tt>, but that's what the class
<tt class="classname">BadFaceValue</tt> is for). Anywhere a
<tt class="classname">Card</tt> object is expected a <tt class=
"type">char</tt> can be passed without confusion, and when the char
represents an invalid denomination, the conversion will fail with
the <tt class="classname">BadFaceValue(char)</tt> exception being
raised.</p>
<p class="c2"><span class="remark">FG: A consequence of that
decision is that functions that take a <tt class=
"classname">Card</tt> argument have to validate the argument and
throw an exception if it is not valid. Throwing an exception is a
runtime event and we should follow the rule of checking things as
early as possible. I think that the <tt class="classname">Card</tt>
constructor from <tt class="type">char</tt> should be <tt class=
"literal">explicit</tt> unless you can provide some cogent reason
why implicit conversion form a char to a Card should be
allowed.</span></p>
<p>The <tt class="classname">Card</tt> class does not need the
<tt class="function">get_numerical_value</tt> function, as the int
conversion operator does the same thing. A <tt class=
"classname">Card</tt> (or <tt class="classname">CardValue</tt> as I
suggested above) object is directly identified with an <tt class=
"type">int</tt> value, and using the <tt class="type">(int)</tt>
cast makes sense in whatever context.</p>
<p class="c2"><span class="remark">FG: I would argue exactly the
other way and remove that conversion operator. I do not want
functions that expect an <tt class="type">int</tt> to accept a
<tt class="classname">Card</tt>. I would apply similar reasoning to
the provision of a <tt class="type">char</tt> conversion operator.
Indeed one major inconsistency in the authors design is that he
inhibits implicit inward conversions while explicitly providing for
the more dangerous implicit outward conversions.</span></p>
<p>Similarly, the class <tt class="classname">BadFaceValue</tt>
does not require the function <tt class=
"function">get_face_value</tt>, as the <tt class=
"methodname">char()</tt> conversion operator does the same thing.
Indeed the program nowhere calls the <tt class=
"function">get_face_value</tt> function, but only uses the
<tt class="methodname">char()</tt> conversion (in the <tt class=
"methodname">Hand::input_hand</tt> function). Strictly speaking
there's no reason for the class <tt class=
"classname">BadFaceValue</tt> at all, as all it is a <tt class=
"type">char</tt> with a default value of <tt class=
"literal">'?'</tt> which is never used, and a <tt class=
"type">char</tt> exception could just as well be thrown in
<tt class="methodname">Card::Card</tt>, and that <tt class=
"type">char</tt> exception caught in the catch block of <tt class=
"methodname">Hand::input_hand</tt>. However I agree with the
author's approach as it improves code clarity. One final point
though - as <tt class="classname">Card</tt> is the only class which
uses the exception perhaps it would be an idea to include the
exception class definition within the scope of the <tt class=
"classname">Card</tt> class. In <tt class=
"methodname">Hand::input_hand</tt> this would mean the catch block
would read <tt class="literal">catch(Card::BadFaceValue
fv))</tt>.</p>
<p>The use of an exception class is a commonly used strategy for
dealing with constructor failures as the constructor cannot return
a value to the client to indicate failure (the client in this case
being the <tt class="function">Hand::input_hand</tt> function - the
<tt class="literal">try</tt> block in that function encloses code
where a <tt class="classname">Card</tt> object is constructed).</p>
<p>As far as I know a semi-colon is not needed after the closing
brace of a namespace declaration, although VC++ 6 accepts it.</p>
<p class="c2"><span class="remark">FG: Strictly speaking, an error
that requires a diagnostic.</span></p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e795" id="d0e795"></a>Hand.h</h4>
</div>
<p>The <tt class="literal">using</tt> directive introduces all
<tt class="literal">std</tt> scoped names into the file's scope,
but the only names needed are <tt class="classname">istream</tt>,
<tt class="classname">ostream</tt>, <tt class="classname">cin</tt>,
<tt class="classname">cout</tt>. using declarations (i.e. using
<tt class="classname">std::cin</tt> etc) for these would
suffice.</p>
<p class="c2"><span class="remark">FG: Even using declarations at
global scope in a header file impose names on all who #include the
header into their own code.</span></p>
<p>The public interface for class <tt class="classname">Hand</tt>
consists of the two functions <tt class=
"methodname">input_hand</tt> and <tt class=
"methodname">show_total</tt> (the client main only calls these two
functions). The other two functions, <tt class=
"methodname">add_card</tt> and <tt class=
"methodname">calculate_total</tt>, should therefore be made
<tt class="literal">private</tt>. I note the declaration of
<tt class="methodname">add_card</tt> specifies a whole <tt class=
"classname">Card</tt> object, but objects should always be passed
by reference, and made <tt class="literal">const</tt> if they are
not intended to be changed by the function. Thus we would have
<tt class="methodname">add_card(const Card &amp; card);</tt> as the
declaration of <tt class="methodname">add_card</tt>. Because of the
operator <tt class="methodname">char()</tt> defined for class
<tt class="classname">Card</tt>, <tt class=
"methodname">add_card</tt> could just as well take a <tt class=
"type">char</tt> parameter, but <tt class="classname">Card</tt> is
clearer as it is a <tt class="classname">vector</tt> of <tt class=
"classname">Card</tt>s that is stored in the object; going from the
user input to creating a <tt class="classname">Card</tt> is where
the <tt class="methodname">char()</tt> conversion should take
place, not in going from a <tt class="classname">Card</tt> to a
collection of <tt class="classname">Card</tt>s. Lastly on
<tt class="methodname">add_card</tt>, as it so short a function it
could be made inline by defining it within the class definition (or
prefixing the definition in <tt class="filename">Hand.cpp</tt> with
the word <tt class="literal">inline</tt>). The functions <tt class=
"methodname">calculate_total</tt> and <tt class=
"methodname">show_total</tt> can be declared as <tt class=
"literal">const</tt> member functions of <tt class=
"classname">Hand</tt> as they never change the member variables of
the object on which they are called.</p>
<p class="c2"><span class="remark">FG: Many sets of coding
guidelines require that, at a minimum, all inline definitions
should be signed off. Furthermore, placing an inline definition in
the <tt class="filename">.cpp</tt> file is at best a waste of time
because the compiler will not see it at the point of
use.</span></p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e919" id="d0e919"></a>Hand.cpp</h4>
</div>
<p>In the function <tt class="methodname">input_hand</tt> the user
is just given the prompt message again when they type in an invalid
number of cards. Thus the <tt class="literal">while</tt> loop
should be restructured to include a helpful error message. The use
of a <tt class="type">char</tt> instead of an <tt class=
"type">int</tt> here reduces some of the stream problems, though
its not watertight. (Incidentally I find stream IO on a command
prompt quite tricky - in Windows programming processing input is
much simpler, as the user can type whatever they want, you can
restrict it to digit characters by specifying a property of the
edit control (in Win32, the <tt class="constant">ES_NUMBER</tt>
control style), and you can query the edit control for how much
data is in its buffer, and so allocate a large enough buffer in
your own program, then get the data into that buffer, and then
examine its contents to see if its acceptable for that particular
input, typically reporting an error message box if its not - a
reasonably straightforward procedure in comparison with using the
stream libraries facilities).</p>
<p>Further on into the <tt class="function">input_hand</tt>
function, where user input is being turned into <tt class=
"classname">Card</tt> objects, the line <tt class=
"literal">add_card(Card(face_value));</tt> could now read
<tt class="methodname">add_card(face_value)</tt>, due to the
removal of <tt class="literal">explicit</tt> in <tt class=
"filename">Card.h</tt>. An exception will be thrown just the same
if a bad face value is entered. I would suggest also that
<tt class="literal">catch(BadFaceValue fv)</tt> be changed to
<tt class="literal">catch(BadFaceValue &amp; fv)</tt> as (unless
someone can enlighten me with a counterexample) whole objects need
never be passed to functions.</p>
<p class="c2"><span class="remark">FG: I do not understand that
last sentence. We should always prefer catch by reference but that
is to avoid potential slicing when an exception thrown has been
derived from the type being caught.</span></p>
<p>In the function <tt class="function">calculate_total</tt> the
calls to <tt class="literal">i-&gt;get_numerical_value()</tt> can
be replaced by <tt class="literal">(int)(*i)</tt>, as a <tt class=
"classname">Card</tt> object (preferably <tt class=
"classname">CardValue</tt> as mentioned above) can be converted to
an <tt class="type">int</tt>.</p>
<p class="c2"><span class="remark">FG: I strongly prefer the use of
a named function. I dislike casts unless they are essential, and
even more strongly dislike old C-style casts. They simply stop the
compiler from helping get code correct.</span></p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e991" id="d0e991"></a>Overall
Structure</h4>
</div>
<p>The author mentioned that the only information needed from the
<tt class="classname">Hand</tt> class was the total hand value. It
could be defined this way, with <tt class="literal">int total;</tt>
replacing the <tt class="literal">vector&lt;Card&gt;</tt>. There
would then be no need for a separate <tt class=
"function">calculate_total</tt> function, and the function
<tt class="function">input_hand</tt> would tally the total score as
the cards were entered, setting a flag <tt class=
"varname">contains_aces</tt> if an ace was detected, and adjusting
the final score (in the new way as the author suggested). In the
region of the <tt class="function">add_card</tt> call in <tt class=
"function">input_hand</tt> the code would thus look like :</p>
<pre class="programlisting">
try{
//...etc...
Card card(face_value); 
    // could except with BadFaceValue
  if (tolower(face_value) == 'a')
    contains_aces = true;
  add_card( card );
  total += card;  
// uses Card's int conversion
}
catch(BadFaceValue &amp; fv){ }
</pre>
<p>This approach would result in a faster execution time (between
the end of the user's input and display of the result - only tiny
fractions of a second in this example - though in real world
applications, a similar trade-off may involve much larger time
scales).</p>
<p class="c2"><span class="remark">FG: I doubt that such an
optimisation will have any significant impact on real code that
involves user i/o. Once, many years ago, I had to very carefully
code a problem where a name being typed in had to be located in a
given list on the fly so that as soon as the possibilities had been
reduced to not more than eight the user would be given the
opportunity to select from that list. These days I would not bother
with any fancy coding because modern platforms would do so much
processing between keystrokes that a simple, easy to maintain,
solution would meet the design requirements.</span></p>
<p>However as two contributors to Code Critque 13 mentioned it is
usually preferable to separate obtaining the user input from
processing it, e.g. by using two separate functions such as the
<tt class="function">input_hand</tt> and <tt class=
"function">calculate_total</tt> functions above. It is less
efficient in terms of execution time, as the same for loop is
traversed twice, but it is clearer to understand, and therefore
preferable if performance is not critical.</p>
<p>Being retrograde, I describe a non-class based solution to the
original problem, which is similar to this solution (has comparable
number of lines of code and separates obtaining user input from
processing it).</p>
<p>Step 1 : Request number of cards in hand (in var <tt class=
"varname">num_cards</tt>), using function <tt class=
"function">GetNoOfCards</tt>.</p>
<p>Step 2 : Call function <tt class="function">bool GetHand(int
num_cards, vector&lt;char&gt; &amp; hand)</tt>, which returns
<tt class="literal">true</tt> if required number of cards in hand
was entered without user cancelling, and <tt class=
"literal">false</tt> if the user cancelled. <tt class=
"function">GetHand</tt> places the entered cards in the vector of
chars passed in if the user didn't cancel.</p>
<p>Step 3 : If user cancelled in Step 2, then skip Steps 4 - 5
below.</p>
<p>Step 4 : Call function <tt class="function">bool
GetHandValue(const vector&lt;char&gt; &amp; hand, int &amp;
hand_value)</tt> which returns <tt class="literal">true</tt> if not
bust (i.e. hand value is &lt;= 21) and <tt class=
"literal">false</tt> if bust (i.e. hand value &gt; 21). Whether
bust or not, the hand value is stored in <tt class=
"varname">hand_value</tt>.</p>
<p>Step 5 : If false is returned in Step 4 above then output &quot;You
busted with : <tt class="varname">hand_value</tt>&quot;, otherwise
output &quot;Your hand is : <tt class="varname">hand_value</tt>&quot;.</p>
<p>Step 6 : Ask user if they want to continue. If yes loop back to
Step 1, else end program.</p>
<p>We then have a <tt class="function">main</tt> that looks
like:</p>
<pre class="programlisting">
int main(void){
  vector&lt;char&gt; hand;
  int hand_value;
  char input;
  do{
    if(GetHand(GetNoOfCards(),hand)){
      if(GetHandValue(hand, hand_value))
        cout &lt;&lt; &quot;Your hand is : &quot; 
            &lt;&lt; hand_value &lt;&lt; endl;
      else
        cout &lt;&lt; &quot;You busted with : &quot; 
            &lt;&lt; hand_value &lt;&lt; endl;
    }
    cout &lt;&lt; &quot;Continue ? (y/n) : &quot; ;
    cin &gt;&gt; input;
  }
  while(tolower(input) == 'y');
  return 0;
}
</pre>
<p>The full code is in the electronic version on our web site.</p>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e1094" id="d0e1094"></a>From The
Harpist</h3>
</div>
<p>More often than not, critiques of source code focus on the code
itself. I think that is often a mistake. We need to get to the
fundamental design issue and when we have a hold of that the code
often writes itself. With this in mind let us look at the source
code Francis presented for critique this time.</p>
<p>A quick read of the code should start raising questions in your
mind. If it is correct to make constructors explicit (which it
generally is) what are those conversion operators doing there? What
is the purpose of the three classes? More fundamentally, what is
the code achieving? So back to the drawing board.</p>
<p>We want to input the denominations (though not suits) of between
two and five cards and evaluate them as a blackjack hand.
Apparently we need not consider special hands, just the best total
that the hand will make. The first question I ask is why ask the
user for the number of cards in the hand? Why not just count them
in? We know we need two and we know that when we have five that is
it. If we are going to count them in we need some way for the user
to signal that the hand is complete. Let me use a common technique
and simply use any invalid key to terminate input. Of course we
will not allow termination until two cards have been put in.</p>
<p>Now let me make a list of the tools I need:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Something to give the user instructions.</p>
</li>
<li>
<p>A function to get an input and validate it.</p>
</li>
<li>
<p>A function to evaluate a hand and store the result (note to
self, I must track the special case of an ace because that is two
valued)</p>
</li>
<li>
<p>An output function</p>
</li>
<li>
<p>A driver.</p>
</li>
</ul>
</div>
<p>Let me write the driver first:</p>
<pre class="programlisting">
int main(){
  try{
    instructions();
    do{
      evalhand eh;
      eh.result();
    } while(again(&quot;Do you have another?&quot;)
  }  
  catch(...) {
    std::cout &lt;&lt; &quot;Stopping \n&quot; &lt;&lt; std::endl;
  }
  std::cout &lt;&lt; &quot;That is it.&quot; &lt;&lt; endl;
  return 0;
}
</pre>
<p>I always put most of my main in a try block so that I will get
clean up if some exception is thrown that I had not prepared for.
It costs little so I can see little reason to do otherwise. Now let
me write the various bits needed to allow that code to compile and
link to produce an executable.</p>
<pre class="programlisting">
void instructions(){
  std::cout &lt;&lt; &quot;Ask me about it.&quot; &lt;&lt; std::endl;
}
</pre>
<p>In real life you implement that function somewhat better, but
you can refine that as you go and easily respond to user problems
with understanding your instructions because you have isolated that
task in its own function. I would rip out all the string literals
and provide them through a file that could be customised for
different human languages. The <tt class=
"function">instructions</tt> function is a special case because it
is all text and so could be provided in English, French, Spanish
etc. versions.</p>
<p>Now what can we deduce from the <tt class="literal">evalhand
eh;</tt> statement? Yes, <tt class="classname">evalhand</tt> must
be a type. So we get (with a little thought):</p>
<pre class="programlisting">
class evalhand {
  int total;
  bool hasanace;
public:
  evalhand();
  void result();
};
</pre>
<p>What has that constructor for <tt class=
"classname">evalhand</tt> got to do? It has to read in data, card
by card until finished keeping a running total, and a record of
whether the hand contains an ace. Reading in a card is a service
routine so we hide it away in the unnamed namespace of the
implementation file for <tt class="classname">evalhand</tt>. I want
to get a value back and a validation code. Something like this:</p>
<pre class="programlisting">
namespace{
  bool get(char &amp; c) {
    std::cin &gt;&gt; c;
    return std::strchr(&quot;23456789tjqkaTJQKA&quot;, c)
  }
</pre>
<p>Note that that string literal used to show valid input
characters may need adjusting for non-English speaking versions.
While I remember, I can also use the following as another service
function:</p>
<pre class="programlisting">
  void validinputs(){
    std::cout &lt;&lt; &quot;Type the first letter of&quot;
          &lt;&lt; &quot; Ace, King, Queen, Jack, Ten&quot;
          &lt;&lt; &quot; and 2 to 9 for the others.&quot;
          &lt;&lt; std::endl;
}
</pre>
<p>I would polish the wording for my release version.&quot;.</p>
<p>It is about time to write the <tt class=
"classname">evalhand</tt> constructor (at file scope):</p>
<pre class="programlisting">
evalhand::evalhand():total(0), hasanace(false) {
  char card;
  std::cout &lt;&lt; &quot;First card please : &quot;;
  while(!get(card)) {
    std::cout &lt;&lt; &quot;Input not recognised\n&quot;;
    validinputs();
  }
  total += value(card, hasanace);
  std::cout &lt;&lt; &quot;Second card please : &quot;;
  while(!get(card)) {
    std::cout &lt;&lt; &quot;Input not recognised\n&quot;;
    validinputs();
  }
  total += value(card, hasanace);
  std::cout &lt;&lt; &quot;Any key other than one&quot;
       &quot;representing a card ends input.\n&quot;
  for(int count=0; count&lt;3; ++count){
    if(!get(card)) break;
    total += value(card, hasanace);
  }
}
</pre>
<p>I am leaving refactoring the common code in the above as an
exercise for the reader. Note that I do not need exceptions. I
avoid exceptions unless the problem detection and solution are
necessarily remote from each other.</p>
<p>I slipped in another service function there so I will need to
add that to my unnamed <tt class="literal">namespace</tt>:</p>
<pre class="programlisting">
  int value(char c, bool &amp; isace){
    int val = 10;
    c = tolower(c);
    if(c=='a'){
      isace = true;
      val = 1;
    }
    if(c&gt;'1' &amp;&amp; c&lt;='9') val = c-'0';
    return val;
}
</pre>
<p>Note that I can skip most of the tests by initialising
<tt class="varname">val</tt> to the value of face cards . The
<tt class="methodname">get</tt> function has already validated the
input.</p>
<p>Now to that member function:</p>
<pre class="programlisting">
void evalhand::result() {
  if(total&lt;11 &amp;&amp; hasanace) total += 10;
  if(total&gt;21) std::cout &lt;&lt; &quot;You busted. &quot;
  std::cout&lt;&lt;&quot;Your total was: &quot; &lt;&lt; total &lt;&lt; '\n';
}
</pre>
<p>Those who have tracked my code to here will realise that there
is one more function to go. Well you should have a function such as
<tt class="function">again</tt> in stock. If you haven't it is time
you wrote one. That gives me an idea. There are dozens of little
utility functions like <tt class="classname">again</tt>. What about
an ACCU library of them? They are tedious to write and many of them
have little catches that need some thought. In this case even
partial internationalisation needs a little care.</p>
<p>That is it. Please feel free to rip into my code and my design.
However next time you do a code review think about the design
issues first. That means you must focus on why the code is being
written. You may not agree with the XP philosophy but there is a
great deal to be said for leaving tomorrow's problems till
tomorrow. Trying to solve them early often leads to undesirable
complexity.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e1198" id="d0e1198"></a>Student
Code Critique 15</h2>
</div>
<p>There is a problem with this code to reverse a given string in
place with the use of pointers. It gives a segmentation fault
whenever it tries to swap two characters in the string. The fault
comes in the line indicated in the following code:</p>
<p>Please note that this is C code so those of you who know that
this problem is trivial in C++ can add the C++ solution but for
competition purposes you need to do two things. First explain and
correct the problem. Then supply a well-structured C solution to
the problem to demonstrate to the student how good code would look.
Note, that this is exactly how any competent instructor should work
- correct the students work and then give a good solution. Better
instructors would ask students to do a code review on the
instructor's own code.</p>
<p>By the way, many systems will actually accept and execute the
student's compiled code producing exactly the output he expects. He
has been lucky that the platform he is using demands higher
standards.</p>
<pre class="programlisting">
#include &lt;string.h&gt;
void swap(char *a, char *b){
  char tmp;
  tmp = *a;
  *a = *b;  
//that is where the seg. fault comes
  *b = tmp;
}
void reverse(char *str){
  char *a, *b;
  for(int i=0; i&lt;strlen(str)/2; i++){
    a = &amp;(str[i]);
    b = &amp;(str[strlen(str)-i-1]);
    printf(&quot;swapping %c &amp; %c...\n&quot; ,*a, *b);
    swap(a, b);
  }
  printf(&quot;the reversed string is: %s\n&quot;, str);
}
main() {
  reverse(&quot;cheese&quot;);
}
</pre></div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
