    <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</title>
        <link>http://accu.org/index.php/journals/1154</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">CVu Journal Vol 14, #1 - Feb 2002 + Student Code Critiques from CVu journal.</span></div>

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

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

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

                     &gt;                         <a href="http://accu.org/index.php/journals/c77/">CVu</a>

                     &gt;                         <a href="http://accu.org/index.php/journals/c116/">141</a>
                    (8)
<br />

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

                     &gt;                         <a href="http://accu.org/index.php/journals/c184/">Journal Columns</a>

                     &gt;                         <a href="http://accu.org/index.php/journals/c183/">Code Critique</a>
                    (39)
<br />

                                            <a href="http://accu.org/index.php/journals/c116-183/">Any of these categories</a>

                    -                        <a href="http://accu.org/index.php/journals/c116+183/">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</h1>
<p><strong>Author:</strong>&nbsp;Administrator</p>
<p>
<strong>Date:</strong> 06 February 2002 13:15:49 +00:00 or Wed, 06 February 2002 13:15:49 +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></h2>
</div>
<p>Sponsored by Blackwells Bookshops in collaboration with
Addison-Wesley and open to all, experts and novices alike.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e22" id="d0e22"></a>No 13: The
Entries</h2>
</div>
<p class="c2"><span class="remark">When I published the source code
I wondered if anyone would notice that it is actually quite
unnecessary to count the aces in order to score a Blackjack (also
known as Vingt-et-Un) hand. Any hand that contains at least one ace
has two possible scores, a minimum and a (minmum+10) because
(minimum+20) will always be a bust and so cannot be an acceptable
score. All we need is a Boolean flag that marks a hand as with or
without an ace. And much to my delight one of you (Tony Houghton)
did so.</span></p>
<p class="c2"><span class="remark">A feature of this competition
was the number of people who just made the deadline (and one missed
it but...). One contributor wondered if I could set longer
deadlines. Actually I doubt that would improve things even if
timing allowed it (note that this column has to be submitted to the
editor in time for him to cut the printed version as necessary, and
after the next issue he will have to do that early enough to allow
the production editor to do her job)</span></p>
<p class="c2"><span class="remark">Another thing that makes it hard
to choose a winner and hard to decide what to cut out of the
printed copy is the wide variety of approaches. Do not stop, that
is part of what this is about. There is no single right
way.</span></p>
<p class="c2"><span class="remark">Because code along with the
article can be helpful but can take a lot of space I have taken
liberties with its format. Because I am too lazy to create too
complete versions, on for print and one for the web both will have
condensed code format.</span></p>
<p class="c2"><span class="remark">Now none of the entries were
pristine examples of coding and several include dubious practices.
However the purpose of this column is to encourage you to read
source code critically. I will be very disappointed if there are
not a number of letters to the editor highlighting over-sights and
taking issue with some of the code in what follows. OK so you do
not get a prize for it, but you do get to become a better
programmer. That should be worth a lot. You also help others to
become better programmers and that should give you a warm
glow.</span></p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e40" id="d0e40"></a>From James Holland
<tt class="email">&lt;<a href=
"mailto:jamie_holland@lineone.net">jamie_holland@lineone.net</a>&gt;</tt></h3>
</div>
<p>To start with, it is best to have the rules of how to find the
value of a blackjack hand spelt out in English. In other words we
need a specification. We can then decide whether the program is
doing what is should. After a bit of hunting I find that the rules
for adding the cards of a blackjack hand are as follows.</p>
<p>The score of a hand is the sum of the values of the cards. An
ace counts as either 11 or one, whichever results in a better score
for the hand. Any face card counts as ten, and any other card
counts as its face value. Any hand with a total greater than 21
&quot;busts&quot; and cannot win.</p>
<p>Well let's have a quick scan through the program to see if we
can understand how it works and to pick out any immediate problems.
After a welcome message the program enters a loop that will end
only when the user doesn't want to have another go. So far, so
good. The first line of the loop is a call to a function named
<tt class="function">number</tt>. The function takes a single
parameter of type <tt class="type">int</tt> as can be gleaned from
the prototype. The <tt class="type">int</tt> value is passed by a
variable by the name of <tt class="varname">num_cards</tt>. This is
where things aren't quite right. The bad news is that <tt class=
"varname">num_cards</tt> has not been initialized to any particular
value. Its value could be anything (within the range of an
<tt class="type">int</tt>). The good news is that when this unknown
value is passed to the function <tt class="function">number</tt>,
the function does not take any notice of it anyhow. Of course this
is not really good news because it shows that the student has got
somewhat muddled in defining the function, but at least it will not
prevent the program from working.</p>
<p>What the student should have done is to declare the function
number with no parameters and to have defined <tt class=
"varname">num_cards</tt> as a local variable within the <tt class=
"function">number</tt> function. With this out of the way we will
press on.</p>
<p>The function <tt class="function">number</tt> returns with the
number of cards as entered by the user. This number must be within
the range two to five inclusive. If the number entered by the user
is not within this range the function will insist that the user
enters another number.</p>
<p>The main function now repeatedly calls <tt class=
"function">card_val</tt>, once for each card in the hand. The
sequence number of each card is passed to the function by means of
an int parameter. The <tt class="function">card_val</tt> function
invites the user to enter a card. It then calculates and returns
the value of the card. Things get a little confusing here because
the student has declared a variable within the <tt class=
"function">card_val</tt> function with the same name as the
function, namely <tt class="varname">card_val</tt>. Another name,
such as <tt class="varname">value_of_card</tt> would have been a
better choice.</p>
<p>While we are on the subject of the naming of variables, there
are one or two things that should be born in mind. The name of the
variable should reflect the use put to the variable. The name
should be clear and easy to read. Non-standard abbreviations should
be avoided. There is no reason to call local variables <tt class=
"varname">card_val</tt>, for example, when the name <tt class=
"varname">card_value</tt> does not take a great deal more typing
and is explicit. I actually agree with the general way the student
constructs variable and function names, i.e. a short phrase, all in
lower case and separated with underscores. In every day life most
text is written in lower case and separated with spaces and this,
presumably, is what most people are used to.</p>
<p>There is a slight complication if the user chooses an ace for a
card. The number of aces entered has to be counted for use later
on. This is where the student comes unstuck.</p>
<p>The student has declared a variable within the <tt class=
"function">card_val</tt> function with the name of <tt class=
"varname">aces</tt>. Now, there is already a variable with the name
<tt class="varname">aces</tt> declared in the <tt class=
"function">main</tt> function. This is bound to cause confusion.
The <tt class="varname">aces</tt> variable that was declared in the
<tt class="function">card_val</tt> function is created and
initialised to zero each time the function is called. It is a
reference to this variable (that has the value zero) that is passed
to <tt class="function">ace_count</tt> (or as the student
incorrectly types, <tt class="literal">ace_card</tt>). The
<tt class="varname">aces</tt> variable (the one declared in
<tt class="function">card_val</tt>) is incremented by one by the
<tt class="function">ace_count</tt> function. Unfortunately, when
the <tt class="function">card_val</tt> function finally returns,
the <tt class="varname">aces</tt> variable no longer exists. What
should be used is the <tt class="varname">aces</tt> variable that
was declared in the <tt class="function">main</tt> function. There
is no need to declare the <tt class="varname">aces</tt> variable in
<tt class="function">card_val</tt> at all.</p>
<p>The only problem now is that <tt class="varname">aces</tt>
declared in <tt class="function">main</tt> is not directly
accessible from within <tt class="function">card_val</tt>. One way
to get out of that problem is to add another parameter to
<tt class="function">card_val</tt> that passes the <tt class=
"function">main</tt> <tt class="varname">aces</tt> variable by
reference. The call to <tt class="function">card_val</tt> would
have to be modified as well, of course.</p>
<p>Having summed the value of all the cards within the hand, the
<tt class="function">main</tt> function now attempts to display the
value of the hand. So far the program has assumed that all aces are
worth 11 points each. This is the correct thing to do as long as
sum does not exceed a value of 21. If the hand does exceed 21,
then, for each ace in the hand 10 points can be subtracted until
the value of the hand becomes 21 or less. This is where the
<tt class="function">hand_value</tt> function comes in. I think the
student was getting a bit fed up at this stage as there are a
couple of simple errors in as many lines here. The definition of
the function is called <tt class="function">new_value</tt> whereas
the prototype and the call refer to a function called <tt class=
"function">hand_value</tt>. Presumably, the definition should be
written as <tt class="function">hand_value</tt>. The <tt class=
"function">hand_value</tt> function contains a <tt class=
"literal">while</tt> loop that refers to <tt class=
"varname">ace_counts</tt>, I think what the student really means is
<tt class="varname">aces</tt>.</p>
<p>Now that all these little problems have been put right, does the
program work? Well, not quite. The number of aces is not set to
zero when the user wishes to choose another hand. The student has
remembered to zero the total value of the hand, but not the number
of aces. After rectifying this omission, we now have a working
program (I think).</p>
<p>There are, however, one or two things that could be done to
improve the general structure of the program. There is a rule of
thumb that states that variables should be declared as late as
possible, i.e., as near to the point of use as possible. This helps
when maintaining the program; you don't have to look so far to find
the declaration of variables. It also keeps the scope of variables
limited to where they are used. There is no point in spreading
their influence too far a field. <tt class=
"varname">num_cards</tt>, <tt class="varname">total</tt> and
<tt class="varname">aces</tt> and be declared and initialised
within the <tt class="literal">do</tt> loop of <tt class=
"function">main()</tt>, for example.</p>
<p>Code layout is always a matter of personal taste, but I would
like to see a space either side of an operator, such as <tt class=
"literal">value = 10</tt>. I also prefer opening and closing braces
to be vertically aligned. I simply do not understand the idea of
having the opening brace and the end of controlling line. It makes
working out what code constitutes a block much more difficult. I
know many experts use this asymmetric approach, so if anyone can
explain to me how it makes the code more readable I would like to
hear about it. (I can see that the asymmetric approach is of some
use when printing code as it uses one less line per pair of braces
on the written page. <i><span class="remark">Exactly, so you should
not judge layout on the basis of what is printed. Layout should be
a feature of function not religion. Francis</span></i>)</p>
<p>The code that deals with displaying the total hand could be
tidied up a bit. If <tt class="function">new_hand</tt> was called
regardless of the calculated total, then the system of nested
<tt class="literal">if</tt> statements could be simplified and now
becomes as shown below.</p>
<pre class="programlisting">
total = hand_value(total, aces);
if (total &lt;= 21)
  cout &lt;&lt; &quot;\nYour hand is: &quot; &lt;&lt; total &lt;&lt; &quot;.&quot;;
else
  cout &lt;&lt; &quot;\nYou busted with &quot; &lt;&lt; total;
</pre>
<p>It does not matter if <tt class="function">hand_value</tt> is
called with total less than or equal to 21, as it will return
immediately with the same value as <tt class=
"varname">total</tt>.</p>
<p>It is useful to know that, within a <tt class=
"literal">switch</tt> statement, a <tt class="literal">case</tt>
can have more than one label. In this way, duplicated code can be
avoided, as shown below.</p>
<pre class="programlisting">
case 't': case 'j': case 'q': case 'k':
  value = 10; break;
</pre>
<p>Here is my version.</p>
<pre class="programlisting">
#include&lt;cctype&gt;
#include&lt;iostream&gt;
using namespace std;
int card_val(int card_no, int &amp; aces);
int number();
int ace_count(int &amp; aces);
int hand_value(int total, int aces);
int main(){
  cout &lt;&lt; &quot;\nWelcome to Blackjack Counter.\n&quot;;
  char again;
  do {
    int num_cards = number();
    int total = 0;
    int aces = 0;
    for (int card_no = 1; 
        card_no &lt;= num_cards; card_no++)
      total += card_val(card_no, aces);
    total = hand_value(total, aces);
    if (total &lt;= 21)
      cout&lt;&lt; &quot;Your hand is: &quot; &lt;&lt; total;
    else
      cout&lt;&lt; &quot;You busted with &quot; &lt;&lt; total;
    cout &lt;&lt; endl;
    cout &lt;&lt; &quot;Do you wish to continue?\n&quot;;
    cout &lt;&lt; &quot;Enter 'Y' (Yes) or 'N' (No): &quot;;
    cin &gt;&gt; again;
  } while ((again == 'Y') || (again == 'y'));
  return 0;
}
int number(){
  int num_cards;
  do {
    cout &lt;&lt; &quot;How many cards do you have? &quot;;
    cin &gt;&gt; num_cards;
    if ((num_cards &lt;= 1) || (num_cards &gt;= 6))
      cout &lt;&lt; &quot;You must have between 2 and 5
                     cards (inclusive).&quot;;
  } while((num_cards &lt;= 1)||(num_cards &gt;= 6));
  return num_cards;
}
int card_val(int card_no, int &amp; aces){
  bool invalid_card;
  int value;
  do {
    invalid_card = false;
    cout &lt;&lt; &quot;Enter value of card number &quot; 
        &lt;&lt; card_no &lt;&lt; &quot;: &quot;;
    char card_val;
    cin &gt;&gt; card_val;
    switch (tolower(card_val)){
      case 'a':
        value = ace_count(aces); break;
case '2':
&lt;similar lines snipped&gt;
      case '9': value = 9; break;
      case 't': case 'j': case 'q': case 'k':
        value = 10; break;
      default:
      cout &lt;&lt; &quot;Not a valid entry. 
              Please try again. \n&quot;;
      invalid_card = true;
    }
  } while (invalid_card);
  return value;
}
int ace_count(int &amp; aces){
  aces++;
  return 11;
}
int hand_value(int total, int aces){
  while ((total &gt; 21) &amp;&amp; (aces &gt;= 1)){
    aces--;
    total -= 10;
  }
  return total;
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e276" id="d0e276"></a>From Catriona
O'Connell <tt class="email">&lt;<a href=
"mailto:catriona38@hotmail.com">catriona38@hotmail.com</a>&gt;</tt></h3>
</div>
<p>There are several problems with the code as published - some of
which are so odd it looks as if the code has been deliberately
mangled :-)</p>
<p>The function <tt class="function">ace_count()</tt> is declared
and defined, but never referenced. An undeclared and undefined
function <tt class="function">ace_card()</tt> is called from within
<tt class="function">card_val</tt>. I suspect, given the function
signatures and results that the call to <tt class=
"function">ace_card()</tt> should be replaced with a call to
<tt class="function">ace_count()</tt>.</p>
<p>The function <tt class="function">hand_value</tt> is declared,
called by <tt class="function">main</tt>, but never defined. Again
given the signatures and function I suspect that the undeclared
function <tt class="function">new_value</tt> should be renamed
<tt class="function">hand_value</tt>. A more informative name would
indicate that it really recalculates the value of the hand. The
<tt class="function">new_value()</tt> function has a problem with
the logic in that it refers to <tt class="varname">ace_count</tt>
as a variable and not the <tt class="varname">aces</tt> value
actually passed as the second argument.</p>
<p>The function <tt class="function">number()</tt>, takes an
unnecessary argument. While it does mean that a temporary value
need not be used in <tt class="function">number()</tt>, it is
misleading. The function itself should retrieve the number of cards
held by the user, but has insufficient error handling and
duplicates the test for valid input. This would have been better
coded as per The Harpist's code critique in C Vu 13.6 p14 or
equivalently using code based on <tt class=
"function">getInput()</tt> from my code in the same article.</p>
<p>Both <tt class="function">main()</tt> and <tt class=
"function">card_val()</tt> could handle requests for character
input in a cleaner and safer fashion than they do. Again I refer to
the code referenced above for how this might be better done.</p>
<p>The problem with counting aces is rooted in the <tt class=
"function">card_val()</tt> function. The count of the number of
aces held is a local variable in this function, and while it is
updated by the <tt class="function">ace_count()</tt> function, it
is destroyed when <tt class="function">card_val()</tt> returns. As
<tt class="function">card_val()</tt> is called once per card by
<tt class="function">main()</tt> the value of the variable aces in
<tt class="function">main()</tt> will always be zero. Given the
current code structure, it is difficult to find an elegant solution
to the problem, short of using a global variable (yeuch!).</p>
<p>In <tt class="function">card_val()</tt> the large number of case
statements can be simplified to three essential cases - numbers,
tens and court cards and aces. I note in passing that there is a
missing semicolon after the break statement associated with case
'9'.</p>
<p>I think that covers the majority of errors in the code. With
regard to structure I feel that the intertwining of user input and
calculation, and indeed user input from multiple routines is messy.
The solution I have proposed probably betrays my prejudice against
handling user input. In almost all the code I write, it either
never interacts directly with a person or obtains all the
information required &quot;up front&quot; and then proceeds to
completion.</p>
<pre class="programlisting">
// Replacement code to work out the value of a 
// blackjack hand. 
// Catriona O'Connell 23.11.2001
#include &lt;iostream&gt;
using namespace std;
enum ifailValues {Success = 0,
  Error_Too_Few_Cards,  Error_Too_Many_Cards,
  Error_Invalid_Card,  Error_Busted};
char *ifailMessages[] = {&quot;Success&quot;, 
  &quot;Too Few Cards&quot;, &quot;Too Many Cards&quot;, 
  &quot;Invalid Card(s)&quot;, &quot;Busted&quot;};
bool CheckValidCharacters(
    const char * testString, 
    const char * validChars);
int GetBlackjackHandValue(
    const char *cards, int *ifail);
bool CheckValidCharacters(
    const char * testString, 
    const char * validChars){
// Check if the first argument string contains // only characters in the second argument 
// string. Returns true if it is the case,
// otherwise returns false.
  size_t testStringLen;
  testStringLen = strlen(testString);
  if(strspn(testString, validChars) 
          != testStringLen) return false;
  return true;
}
int GetBlackjackHandValue(
    const char *cards, int *ifail) {
// Returns the value of a blackjack hand. The 
// value returned is the sum of the value of 
// the cards held, if all the cards are valid 
// and the number of cards is within the 
// presecribed limits. In the event of the 
// hand being invalid, ifail is set to one of 
// the enumerated ifailValue values.
  int cardsLen;
  int handValue = 0;
  int aceCount = 0;
  *ifail = Success;
  cardsLen = strlen(cards);
// Handle simple error cases by setting the 
// ifail status value and returning a hand 
// value of zero.
  if(cardsLen &lt; 2){
    *ifail = Error_Too_Few_Cards;
    return 0;
  }
  if(cardsLen &gt; 5) {
    *ifail = Error_Too_Many_Cards;
    return 0;
  }
// Check that all the cards held are valid.
  bool validHand = CheckValidCharacters(cards,
                   &quot;23456789tTjJqQkKaA&quot;);
  if(!validHand) {
    *ifail = Error_Invalid_Card;
    return 0;
  }
// Now that we've checked the pre-conditions,
// calculate the value of the cards held. For 
// numeric cards, we use the fact that the 
// characters representing the digits are 
// required to be contiguous and in the 
// expected collation order. For ten and 
// picture cards we add 10. For aces, we add 
// 11, but retain a count of the number of 
// aces, in case we need to use the 
// alternative lower value of 1, to attempt to 
// reduce a busted hand to an acceptable one.
  while(*cards)  {
    switch(*cards){
    case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8':
    case '9':
      handValue += (*cards-'0'); break;
    case 't': case 'T': case 'j': case 'J': 
case 'q': case 'Q': case 'k': case 'K':
      handValue += 10; break;
    case 'a': case 'A':
      handValue += 11; aceCount++; break;
    }
    cards++;
  }
// If the hand is busted and there are any 
// aces, then substitute the value 1 for 11, // while the value of the hand is over 21 and 
// there are still unconverted aces remaining.
  while((handValue &gt; 21) &amp;&amp; (aceCount&gt;=1)) {
    aceCount--;
    handValue -= 10;
  }
// If despite the above, the value of the hand 
// is over 21, return the value but set the 
// ifail status value to reflect that.
  if(handValue &gt; 21) *ifail = Error_Busted;
  return handValue;
}
int main() {
  char *testString[] = {&quot;8&quot;, &quot;ak2233&quot;,
               &quot;aaaa2&quot;,&quot;kkaa4&quot;,&quot;2234f&quot;};
  int ifail;
  int result;
  for(int i=0; i&lt;5;++i) {
    result = GetBlackjackHandValue(testString[i], &amp;ifail);
    cout &lt;&lt; testString[i] &lt;&lt; &quot; &quot; &lt;&lt; result &lt;&lt; &quot; &quot; &lt;&lt; ifailMessages[ifail] &lt;&lt; endl;
  }
  return 0;
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e371" id="d0e371"></a>Caliv Nir
<tt class="email">&lt;<a href=
"mailto:shanir@netvision.net.il">shanir@netvision.net.il</a>&gt;</tt></h3>
</div>
<p>At first, as in the past I want to apologize for my English,
please be patient.</p>
<p>{<i><span class="remark">At the author's request I have cleaned
it up for him, but I can assure you that it was much better than my
Hebrew &lt;g&gt; Francis</span></i>}</p>
<p>At last I got the courage and time (new baby boy :) to do a
critique. I am neither an authority nor a C++ guru, like the
amazing people who write here, just a student, so writing this
critique is based on my own personal experience.</p>
<p>After reading so many books, columns and articles about C++ it
was very hard to start this critique. I have in my mind all, what
you should do and what you shouldn't do, and writing for such
audience like you its very, well, brrrr.</p>
<p>But then I thought (hell) why not, let me try it (and I would
even appreciate a critique on my critique), let see if I can
contribute a little.</p>
<p>Reading the code and trying to &quot;fix&quot; it, I've decided on some
key guidelines that I will follow:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>First of all make the code work.</p>
</li>
<li>
<p>Readability of the code is most important</p>
</li>
<li>
<p>This code is not for guiding a rocket missile, so although I
would love to use the most efficient code, it would not come over
readability.</p>
</li>
<li>
<p>Reading the first two lines of code it's clear that it's author
wants to use C++, although it could easily be written in C. I will
keep with C++ and not be temped to convert it into OOP, because
it's a critique, no?</p>
<p>But I will try to use more &quot;C++ as a better C&quot; features in the
code.</p>
</li>
</ul>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e406" id="d0e406"></a>Fixing the
bugs:</h4>
</div>
<div class="orderedlist">
<ol type="1">
<li>
<p>Fixing a typo (to be able to build the program):</p>
<p><tt class="function">hand_value</tt> should be replaced with
<tt class="function">new_value</tt></p>
</li>
<li>
<p>In <tt class="function">new_value</tt> function:</p>
<pre class="programlisting">
while((total&gt;21) &amp;&amp; (ace_count &gt;= 1 ))
</pre>
<p>Oops, <tt class="varname">ace_count</tt> ?? <tt class=
"function">ace_count</tt> is a function name. The author probably
meant to use <tt class="varname">aces</tt> but...</p>
<p>What a nasty bug, my VC++6 with warning level of 4, didn't make
a sound, well we better be careful. The right line is then:</p>
<pre class="programlisting">
while((total&gt;21) &amp;&amp; (aces &gt;= 1 ))
</pre></li>
<li>
<p>Now for the aces counting problem.</p>
<p>The author uses the <tt class="varname">aces</tt> variable in
<tt class="function">main</tt> to keep track of the aces count.
Several functions use and try to update aces, but here comes the
bug (bugs actually). The author has problems with his reference
passing.</p>
<p>The default of passing variables in C and C++ is by value,
meaning that, only the variable's value is passed, and not the
variable itself.</p>
<p>Actually, copying the variable that was passed to the function
does it, any attempt to modify it will be seen only in its function
scope, but not outside the function. Let us see an example:</p>
<pre class="programlisting">
void tryMe ( ){
  int x = 5;
  int y = 5;
  incMeByVal(x);
  incMeByRef(y);
  std::cout &lt;&lt; &quot;x=&quot; &lt;&lt; x &lt;&lt; std::endl;
  std::cout &lt;&lt; &quot;y=&quot; &lt;&lt; y &lt;&lt; std::endl;
}
void incMeByVal( int x ){
  ++x;
}
void incMeByRef( int&amp; y ){
  ++y;
}
</pre>
<p>The output of course is :</p>
<pre class="programlisting">
x=5
y=6
</pre>
<p><tt class="varname">x</tt> was sent by value therefore
<tt class="function">incMeByVal</tt> copied it and modified its
copy and not the &quot;original&quot; <tt class="varname">x</tt>. <tt class=
"varname">y</tt> was sent by reference so <tt class=
"function">incMeByRef</tt> worked on the same object that
<tt class="function">tryMe</tt> created, and was able to modify
it.</p>
<p>Well, the only difference is a small '&amp;' and look what it
does!</p>
<p>Back to our code, lets fix the reference problems:</p>
<p><tt class="function">new_value</tt> should get <tt class=
"varname">aces</tt> by reference so it can modify <tt class=
"varname">aces</tt> also in main's scope. So <tt class=
"function">new_value</tt> signature becomes:</p>
<pre class="programlisting">
int new_value (int total, int&amp; aces );
</pre>
<p><tt class="function">card_val</tt> also needs to modify aces,
but instead of modifying <tt class="function">main</tt>'s
<tt class="varname">aces</tt>, it creates it's own variable and
sends it to <tt class="function">ace_count</tt>, as soon as
<tt class="function">card_val</tt> terminates, all it local
variables are destroyed and <tt class="varname">aces</tt> is one of
them, leaving <tt class="function">main</tt> with un-updated
<tt class="varname">aces</tt>. <tt class="function">card_val</tt>
should be change to get <tt class="function">main</tt>'s <tt class=
"varname">aces</tt> by reference so it could update it
correctly.</p>
<p>So, <tt class="function">card_val</tt> should remove its local
<tt class="varname">aces</tt> variable and <tt class=
"function">card_val</tt> signature becomes:</p>
<pre class="programlisting">
int card_val(int card_no, int&amp; aces);
</pre>
<p>and <tt class="function">main</tt> should call it like:</p>
<pre class="programlisting">
total+=card_val(card_no,aces);
</pre></li>
</ol>
</div>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e561" id="d0e561"></a>My comments
about general structure :</h4>
</div>
<div class="orderedlist">
<ol type="1">
<li>
<p><span class="bold"><b>Starting with line number
3.</b></span></p>
<pre class="programlisting">
using namespace std;
</pre>
<p>So many programmers use it, many even think that they must do it
after including <tt class="literal">&lt;iostream&gt;</tt> (by the
way, great, the code uses standard headers!).</p>
<p>Doing so just ruins the whole purpose of <tt class=
"literal">namespace</tt>. The few times that you need to use
<tt class="literal">std::</tt> in this code doesn't give you any
excuse for using it. We are just polluting the global namespace
with all that <tt class="literal">&lt;iostream&gt;</tt> contains,
and it's a lot!.</p>
<p>Use <tt class="classname">std::cout</tt>, <tt class=
"classname">std::cin</tt> etc. and don't use using <tt class=
"literal">namespace std;</tt></p>
<p>If you are really lazy :-) , or the number of <tt class=
"classname">cout</tt>'s in your code is so great, let's be more
selective and use :</p>
<pre class="programlisting">
using std::cout;
using std::endl;
</pre>
<p>instead.</p>
</li>
<li>
<p>As my lecturer (again, thanks Dr. Kimchi) always said ... &quot;make
a function do only one thing!&quot;, I think it's the most important
guideline in programming style. Follow it and you get more
readable, maintainable &amp; reusable code. The first thing that
bothers me while reading this code are functions that do a lot of
things.</p>
<p>Look at <tt class="function">main</tt>, what a whole bunch of
stuff this function does</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>display a welcome message</p>
</li>
<li>
<p>playing the game</p>
</li>
<li>
<p>looping for more games</p>
</li>
<li>
<p>get user input for continuing with the game</p>
</li>
<li>
<p>checking and activating new_value when it's needed</p>
</li>
</ul>
</div>
<p>Wow, really lots of things.</p>
<p>My recommendation stick with one task per function, write your
self a list of tasks and make a function do only one thing.</p>
<p>If you practice it, you will gain the ability to sense when a
new function is needed in the future (for example when I write an
inner loop, all my senses is telling me, mmm does it really fit
here? ).</p>
</li>
<li>
<p><span class="bold"><b>Code duplication</b></span></p>
<p>The main enemy of maintainable and bug free code. When you
duplicate you copy-paste your bugs! don't do it.</p>
<p>Why do double checks of :</p>
<pre class="programlisting">
if (total &lt;=21)
</pre>
<p>or</p>
<pre class="programlisting">
(num_card &lt;= 1 || num_card &gt;= 6)
</pre>
<p>If you want to change something in the future you should do it
twice. If a bug crept into those conditions you have duplicated it,
yes, just like a virus.</p>
<p>Use functions instead, yes, a function that checks if your
number of cards is in the proper bounds. Right, for all of you
efficiency maniacs, it will make another function call (you can
make it inline if you like), but as I mentioned before, it's not a
real-time, need to be super fast application, right?</p>
</li>
<li>
<p><span class="bold"><b>Magic numbers,</b></span></p>
<p>Don't we love them? Numbers that seem to us the most trivial
thing, numbers that whoever reads the code will always understand
where they come from.</p>
<p>It's an illusion, magic numbers are a maintenance nightmare,
every one after a short period forgets where they come from and
they are the cause of so many bugs. A number needs to be changed
and now I must scan all my code to replace it, and who can decide
if that number is that special number that needs to be change or
it's another misplaced number that another programmer use?</p>
<p>Don't use numbers in your code (or at least, try to minimize the
use of explicit numbers - try a game that I played with some
students in the past, who can write a program with the fewest
numbers).</p>
<p>Use <tt class="literal">const</tt> in C++, or <tt class=
"literal">#define</tt> in C. Define your constants only once and
use their readable text form. Then when you need to change a
constant simply change the constant definition and voila ... For
example instead of 2, 5, 11, 21 use :</p>
<pre class="programlisting">
const int maxNumberOfCards(5);
const int minNumberOfCards(2);
const int ace(11);
const int blackJack(21);
</pre>
<p>Isn't it clearer to see <tt class="constant">ace</tt> instead of
11 in your code ?</p>
</li>
<li>
<p>Believe it or not but most of the time the code talks to it's
reader. The simple switch .. case can say more then you can imagine
and not only to choose the proper value. For example, instead of
:</p>
<pre class="programlisting">
case 't': value = 10; break;
case 'j': value = 10; break;
case 'q': value = 10; break;
case 'k': value = 10; break;
</pre>
<p>write :</p>
<pre class="programlisting">
case 't' :
case 'j' :
case 'q':
case 'k': value = 10; break;
</pre>
<p>Why ? Well, not only have I typed less, not only have we removed
code duplication, but I also said something, I've said that ten,
jack, queen and king have the same value in BlackJack and it's
10.</p>
</li>
<li>
<p>Ok, I've said that in this code I prefer readability over
efficiency, but in places that it doesn't hurt readability you must
always think on how it could be done better. I don't want to enter
here the wonderful world of effective C++ (thanks Scott Meyers for
your great work) but it's worth mentioning that habits are hard to
break, but you break them if you try really hard, and have someone
to remind you all the time.</p>
<p>Well here am I as a one that broke the habit of using postfix ++
whenever I can avoid it. Prefix ++ is more efficient the postfix
++, right, in native types like <tt class="type">int</tt> it's
hardly worth mentioning, but that all about breaking habits, use
prefix ++ all the time, then you will not forget and use it when it
really matters. I will not go into the details because it was
written so many times before, but I only say that postfix ++ most
of the time creates a temporary object.</p>
<p>So when writing in C++, try to use prefix ++ when ever you can.
After the 1000th time you will remember it ...</p>
<p>So replace:</p>
<pre class="programlisting">
aces++ ;
</pre>
<p>with:</p>
<pre class="programlisting">
++aces ;
</pre></li>
<li>
<p>You chose to write in C++, so why don't you use its ability to
declare variables when you need them, and not at the start of block
used to be required in C?</p>
<p>Seeing the variable declaration and initialization close to the
place you use it, does not make you go up the source file and look
for this variable. It helps you to avoid forgetting initialization
and it's very convenient when you write the code. So again try to
drop the old habit from C and use the freedom of C++. For example:
you can alter the for loop in main to be:</p>
<pre class="programlisting">
for(int cardNumber = 1 ; 
cardNumber &lt; numberOfCards; ++ cardNumber) {
// ...
}
</pre>
<p>Notice that I also change the variable names, personally I hate
using '_' but that is not the important thing, don't be cheap in
letters, be more readable, name the variable <tt class=
"varname">numberOfCards</tt> (or for the '_' fans <tt class=
"varname">number_of_cards</tt> ) and not <tt class=
"function">num_cards</tt>. Remember that the one who will read and
maintain your code is not always familiar with your short
names.</p>
<p>Oh, by the way did you notice the prefix ++ ?</p>
</li>
<li>
<p><tt class="classname">std::endl</tt> .</p>
<p><tt class="constant">endl</tt> - end line , much more readable
(though not perfect) then '\n'. Right we all come from C, C++, Java
etc. but what if we come from Visual Basic?, Who wants to see that
strange things as '\n'. I am not saying stop using it, it's silly,
but when you have an option prefer <tt class=
"classname">std::endl</tt> to print out a new line.</p>
<p>Wow, I hear you back there shouting and typing a fast replay,
(yep) but <tt class="classname">std::endl</tt> do more, it also
flushes the stream, well I know but here the battle of readable vs.
efficient ends with readability with the upper hand, sorry. (if you
insist make your own manipulator, make it inline what ever you
want, but be ... : ) you got it - readable)</p>
<p>{<i><span class="remark">It is a matter of developing good
habits. <tt class="classname">std::endl</tt> seems OK in this
context, but it can be bad news when writing to such things as
files. Francis</span></i>}</p>
</li>
<li>
<p><span class="bold"><b>Comments</b></span></p>
<p>Well I will just say that, I will accept a comment free source
file only in the &quot;Student Code Critique Competition&quot; section of
ACCU, or in a text book that have a full explanation of that code
after the source.</p>
<p>The code that I've attached was stripped of comment so it will
fit the magazine, and I want you to read it to see if it
readable.</p>
<p>{<i><span class="remark">You will have to go to the web site
because James is going to be shouting about me taking over again
&lt;g&gt; Francis. However, I would suggest that if code needs lots
of comments, it is badly written. Just as if a piece of text needs
lots of footnotes it needs rewriting. Francis</span></i>}</p>
<p>Ok, I think I will stop now, one thing I've learnt, too much
critique is as good as no critique at all.</p>
<p>My (remember comment free) source code is on the web site, and I
will be happy to here what you think of it. It's always easier to
critique code then to actually write it yourself.</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e773" id="d0e773"></a>From Simon Swift
<tt class="email">&lt;<a href=
"mailto:spswift@ntlworld.com">spswift@ntlworld.com</a>&gt;</tt></h3>
</div>
<p>First of all the function prototype <tt class=
"function">hand_value</tt> should be <tt class=
"function">new_value</tt>.</p>
<p>In the <tt class="function">main</tt> function the use of
<tt class="varname">card_no</tt> for the <tt class=
"literal">for</tt>-loop would be better if it was defined in the
<tt class="literal">for</tt>-statement and <tt class=
"varname">card_num</tt> would be better though I would have
preferred simply <tt class="varname">i</tt> for a counter.</p>
<p>I think I would have preferred to put the prompt to continue in
a separate function that returned a <tt class="type">bool</tt> then
you could have something like:</p>
<pre class="programlisting">
...
} while (yn_continue() );
...
</pre>
<p>that would tidy up the <tt class="function">main</tt> function a
bit.</p>
<p>Now onto the other functions. First the number function. having
a argument <tt class="varname">num_card</tt> is not needed as it
returns the value entered; it should be declared in the body of the
function. The <tt class="literal">if</tt>-statement could have been
better put as</p>
<pre class="programlisting">
if(num_card &lt; 2 || num_card &gt; 5 )
</pre>
<p>Though the original would work fine. there is no check to see if
the user entered a digit or other invalid character or any flushing
of '\n' characters which could course problems. And finally the
name of the function could be better i.e. <tt class=
"function">number_of_cards();</tt></p>
<p>Now to <tt class="function">card_val</tt> and the <tt class=
"function">ace_count</tt> functions. As Francis pointed out,
there's a problem with <tt class="varname">aces</tt>. Basically it
needs to have an <tt class="type">int</tt> pointer in the parameter
list to access the <tt class="varname">aces</tt> variable and not
define the variable again in the body of the function. In the
<tt class="literal">switch</tt>-statement we have some cases that
receive the same value so these could be allow to drop through
:</p>
<pre class="programlisting">
//....
case 't':
case 'j':
case 'q':
case 'k': value = 10; break;
//....
</pre>
<p>Also you do not need the flag <tt class=
"varname">invalid_card</tt> as setting value to zero would do:</p>
<pre class="programlisting">
while( ! value );
</pre>
<p>The <tt class="function">acs_count</tt> function has a reference
to <tt class="varname">aces</tt> but I think in this case a pointer
would be better though I wonder if we needed that to be put in a
separate function.</p>
<p>Finally after thinking about it I decided that the output was a
bit inadequate and was in need of improvement. This, for me, means
displaying, in English, the cards entered and then the total of my
hand. For the program this means storing what the user enters in an
array. In my example below I use a map to keep and retrieve the
words as needed. This map could than be used to validate the input
and this also allowed me to get rid of the <tt class=
"literal">switch</tt>-statement to find the value of the card. I
have not put in a check to make sure that you cannot enter five of
a kind; It seems a bit unnecessary and with displaying the cards
with the result a user should be able to see that mistake.</p>
<p>So here's my version, as you can see some functions have
changed, gone and new ones added.</p>
<pre class="programlisting">
// blackjack.C
#include &lt;iostream&gt;
#include &lt;cctype&gt;
#include &lt;map&gt;
#include &lt;iterator&gt;
#include &lt;string&gt;
using namespace std;
#define MAX_VAL 21
#define MIN_CARDS 2
#define MAX_CARDS 5
int number_of_cards();
int value_of_hand(int, int *, char *,
               map&lt;char, string&gt; &amp;);
int new_val(int, char *, int);
int card_value(map&lt;char, string&gt; &amp;, char, 
                        int *);
bool yn_continue();
void display_hand(map&lt;char, string&gt;
      &amp;card_kind, const char *hand, 
      int num_cards);
int main(){
  char *str[] = {&quot;ace-low&quot;, &quot;one&quot;, &quot;two&quot;,
     &quot;three&quot;, &quot;four&quot;, &quot;five&quot;, &quot;six&quot;, &quot;seven&quot;,
     &quot;eight&quot;, &quot;nine&quot;, &quot;ten&quot;, &quot;Jack&quot;, &quot;Queen&quot;,
     &quot;King&quot;, &quot;ace-high&quot; };
  char * ch = &quot;A123456789tjqka&quot;;
  map&lt;char, string&gt; card_kind;
// build map to keep of each type
  for(char **s = str, *c = ch; *c; c++, s++ )
    card_kind.insert(map&lt;char,
       string&gt;::value_type(*c , string(*s)));
  cout &lt;&lt; &quot;Welcome to the Blackjack Counter.&quot;
      &lt;&lt; endl;
  do {
    int total = 0, aces = 0;
    int num_cards = number_of_cards();
// storage for cards in hand
    char hand[MAX_CARDS];
    for(int i = 0; i &lt; num_cards; i++ )
      total += value_of_hand(i + 1,
              &amp;aces, hand + i, card_kind);
// if bust with aces in try making them ace-low
    if(total &gt; MAX_VAL &amp;&amp; aces &gt; 0) 
      total=new_val(total, hand, num_cards);
    display_hand(card_kind, hand, num_cards);
    if( total &lt;= MAX_VAL )
      cout &lt;&lt; &quot;Your hand is &quot; &lt;&lt; total 
          &lt;&lt; &quot;.&quot; &lt;&lt; endl;
    else
      cout &lt;&lt; &quot;You Bust with &quot; &lt;&lt; total 
          &lt;&lt; endl;
  } while ( yn_continue() );
  return 0;
}
int number_of_cards() {
  int num_cards;
  do {
    cout &lt;&lt; &quot;How many cards do you have? &quot;;
    cin &gt;&gt; num_cards;
    if(!cin) {
      cout &lt;&lt; &quot;Invalid input: &quot;
          &lt;&lt; &quot;Numeric input only!&quot; &lt;&lt; endl;
    cin.clear();
    while(cin.get() != '\n');
    }
    if(num_cards &lt; MIN_CARDS || 
                  num_cards &gt; MAX_CARDS )
      cout &lt;&lt; &quot;You must have between 2 and 5&quot;
          &lt;&lt; &quot;cards (inclusive).&quot; &lt;&lt; endl;
  }while (num_cards &lt; MIN_CARDS || 
                  num_cards &gt; MAX_CARDS);
  return num_cards;
}
int value_of_hand(int card_num, 
          int *ace_count, char *hand, 
          map&lt;char, string&gt; &amp;card_kind) {
  char card;
  int value = 0;
  do {
    cout &lt;&lt; &quot;Enter value of card number &quot; 
        &lt;&lt; card_num &lt;&lt; &quot;: &quot; &lt;&lt; endl;
    cin &gt;&gt; card;
    while (cin.get() != '\n');
    card = tolower(card);
    value = card_value(card_kind, 
                    card, ace_count);
  }while(!value);
  *hand = card;
  return value;
}
int card_value(map&lt;char, string&gt; &amp;card_kind,
             char card, int *ace_count){
  map&lt;char, string&gt;::iterator it 
                = card_kind.find(card);
  if(it != card_kind.end() ) {
  if(card == 'a' ) {
    (*ace_count)++;
    return 11;
  }
  else if(card == 't' || card == 'j' ||
             card == 'q' || card == 'k' )
return 10;
  else
    return card - 48;
  }
  return 0;
}
int new_val(int total, char *hand, int num) {
  for(int i = 0; i&lt;num &amp;&amp; total&gt;MAX_VAL; i++) {
    if(hand[i] == 'a' ) {
      hand[i] = 'A';
      total-= 10;
    }
  }
  return total;
}
bool yn_continue() {
  cout&lt;&lt;&quot;Do you whish to enter another hand? &quot;;
  char c = cin.get();
  while (cin.get() != '\n');
  return ( c == 'y' || c == 'Y' );
}
void display_hand(map&lt;char, string&gt; &amp;card_kind, const char *hand, int num_cards){
  cout &lt;&lt; &quot;In your hand you have cards:&quot; 
      &lt;&lt; endl;
  for(int i = 0; i &lt; num_cards; i++ ){
  map&lt;char, string&gt;::iterator it
            = card_kind.find(hand[i]);
    if(it != card_kind.end())
      cout &lt;&lt; (*it).second &lt;&lt; endl;
  }
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e878" id="d0e878"></a>From Simon
Sebright <tt class="email">&lt;<a href=
"mailto:simonsebright@brightsoftware.freeserve.co.uk">simonsebright@brightsoftware.freeserve.co.uk</a>&gt;</tt></h3>
</div>
<p>I always feel guilty about not entering. Here is my approach to
the problem. I hope it is seen as an attempt to make you think. The
lecturing style should be considered as a literary device. That is
assuming I am entering the (Student Code) Critique and not the
Student (Code Critique) competition, although both are equally
valid. It is actually the eleventh hour. For some reason, my
magazine had been lying undetected and I read the code critique
competition the day before the due date. Today is that date, and I
write hurriedly before I turn into a pumpkin.</p>
<p>Whilst driving between A and B this morning, I was trying to
crystallise the essence of what I might write. Note that I was
neither reading on the motorway nor have I a photographic memory.
My approach is going to be to get across to the student things that
from my experience will benefit their rite of passage. I come from
a background of little formal training in either C++ or the
standard libraries. However, I have had the benefit of working for
more than one modelling company and have been in positions of,
albeit minor, influence within them. So, I'm not going to pick
holes in things a student should know, but from the standpoint of a
senior technical person for whom the student had produced the code
(and who must deliver the code to another party).</p>
<p>Let's suppose my brief was, &quot;Write me a program to workout the
value of a blackjack hand, and demonstrate that it works&quot;. It would
appear to me that the first thing this student did was to switch on
a computer and create main.cpp (or whatever the listing is). Right
we start with <tt class="function">main()</tt>...</p>
<p>What are you doing? Switch it off. My god, don't you want to
think about it? Take a drive for a few hours. Whatever. I would
expect that the brief should first need to be clarified. What do
you mean by a &quot;program&quot;? What use is it to be put to? What kind of
test-harness would you like? My answer: I want a &quot;class&quot; I can
include in <span class="bold"><b>my</b></span> program to add up
the values of blackjack hands. Maybe it's in a DOS window, maybe I
use it in an activeX control. Furthermore, I would like a test
harness &quot;class&quot;, which is also reusable, so that I (or rather you)
can test your evaluation class. So, we call these <span class=
"emphasis"><em>Blackjack Evaluator</em></span> and <span class=
"emphasis"><em>Blackjack Test Harness</em></span>. Your deliverable
program will also have some controlling class, let's call it
<tt class="classname">main</tt>. I don't know, but I may have
already raised eyebrows. Have I insulted the student? I know you
want to prove that you can write an algorithm, but that's not the
deliverable. We'll get there in a minute. Given that we'd like to
separate interface and implementation, we now have five files for
the student - main.c, Blackjack Evaluator.h &amp; c, Blackjack Test
Harness.h &amp; c. Note the judicious use of capital letters. Now,
on our class diagram, we have drawn a relationship from the
controller to the test harness and from the test harness to the
evaluator. These are uni-directional, so we have one file including
the other. In main.c, we have <tt class="literal">#include
&quot;Blackjack Test Harness.h&quot;</tt> and in the test harness
implementation file, we have <tt class="literal">#include
&quot;Blackjack Evaluator.h&quot;</tt>. Note that there is no backward
inclusion going on i.e. that the user of the evaluator does not
need the test harness.</p>
<p>So, what next? Well, the blackjack evaluator needs something to
evaluate. So, we have a function &quot;Evaluate Hand&quot;. This would seem
to be one of the things <tt class="function">main</tt> is doing.
What parameters should it take? Using noun-analysis, we conclude it
must be a &quot;Hand&quot;. Another class, representing a hand of cards, that
is a collection of somethings. What? &quot;Card Values&quot;. I'm not up on
stl, so I don't know the most appropriate container class to use.
It might be nice to have it ordered so that busting could be given
in more detail. A list? A vector? You tell me.</p>
<p>I now see a potential problem, we can't just ask for a hand and
then evaluate it, as it might be the case that a part of that hand
was already over the total allowable, so our test harness needs to
keep calling the evaluate as it grows the hand. This means that
each card is potentially counted more than once. Well, if this
program is so abominably slow that this is unacceptable, then my
brief was wrong (or rather the constraints were not documented).
It's interesting to note here that although my algorithm is
non-linear, I know the limits of it (5 cards maximum). We couldn't
do this for a hand of undefined length without cause for
concern.</p>
<p>Having expounded, I realise I am not criticising the code in the
traditional sense. Line 31, missing semi-colon. Tut, tut. I won't
continue the above train of thought to the bitter end, perhaps I
can now apply some more specific comments, but still along the
lines of standing back from the issue of being a human
compiler.</p>
<p>The first thing I object to is a function called <tt class=
"function">number</tt>. Meaningless. <tt class=
"function">GetNumberOfCards</tt> is my best offering after a few
pints of homebrew. Why does it take an in-parameter? No reason that
I can see apart from not wanting to declare (and initialise) a
local variable.</p>
<p>Next function, <tt class="function">card_val</tt>. The name is
better. <tt class="function">GetCardValue</tt> would be better, but
perhaps you are feeling sheepish by now, so we'll be kind (but can
I recommend that you take a touch typing course instead of playing
computer games?). But, again, why the in-parameter? So you can tell
the user which card they are entering. Fair enough given this
structure, but in my ideal structure, we'd have one lump looking
after getting the card values from the user and another working out
the value of the hand. There are uninitialised variables here. It
makes me shiver. Yes, they are set up in this case, well, all apart
from value when the user enters something that invokes the default
case of the switch statement. I can quite accept that there are
people who could look at the code and say, &quot;In this case it doesn't
matter&quot;. But, I don't think you should have had to get someone to
go that far. There is a problem in assigning a sensible initial
value. I usually go for zero on numerical variables unless the
logic dictates something specific.</p>
<p><tt class="function">ace_count</tt>. An admirable function,
provided it counts the aces in a hand, which it doesn't. This
function as implemented should be called <tt class=
"function">IncrementNumberAndReturnEleven</tt>. Enough said, I
think.</p>
<p><tt class="function">new_value</tt>. Yes, it does get a new
value, but so would a random generator. What is this function
doing? It's working out a refactored value based on the fact that
instead of busting, you can count an ace as 1 instead of 11. A good
name for this function escapes me. <tt class=
"function">GetMaxNonBustTotal</tt> would be a first stab. Not that
long really. I typed it in a second or two.</p>
<p>I've now run out of code. It would seem I have been reduced to
the level I wanted to avoid. I don't see how it would compile and
link:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Where is <tt class="function">hand_value()</tt>, I assume you
meant <tt class="function">new_value()</tt></p>
</li>
<li>
<p><tt class="function">card_val()</tt> calls <tt class=
"function">ace_card()</tt> which I assume should be <tt class=
"function">ace_count()</tt></p>
</li>
<li>
<p><tt class="function">new_value()</tt> references <tt class=
"function">ace_count</tt> as a function pointer rather than a
function call return value. I assume that the formal parameter
<tt class="type">int</tt> aces was meant here. Presumably this will
always be greater than or equal to one and thus I would assume that
all hands will be able to be refactored to a non-bust value.</p>
</li>
</ol>
</div>
<p>A general point, Mr/Ms Student: Your code should compile and
link, and do so with no warnings. You might &quot;know about that one&quot;,
but when you leave for higher echelons, your successor might not. I
might not, you might not in a year's time.</p>
<p>I sincerely hope that by thinking about the problem in the way I
have eluded to above, a student would largely escape the nasties
here. Name your functions well, and only give them the parameters
they need. My class modelling would have applied to C, C++, in fact
any language for which you could devise a suitable mapping between
logical classes and code units. I may have missed the things that
Francis was getting at, I may have picked on things that weren't a
problem, but then, that's my point - it's difficult to analyse a
mess.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e987" id="d0e987"></a>From: Lewis
Everly <tt class="email">&lt;<a href=
"mailto:le_everly3@yahoo.com">le_everly3@yahoo.com</a>&gt;</tt></h3>
</div>
<p>After looking at the code I could see some visible syntax
problems. I'm sure the code would not compile as is. After
repeatedly looking at the code these are the things I have problems
with or would like to improve on.</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>I would not have a parameter for the number function. I think
the number function should look like this.</p>
<pre class="programlisting">
int number(){
  int num_cards = 0;
  while(true){
    cout &lt;&lt;&quot;\nHow many cards do you have? &quot;;
    cin &gt;&gt; num_cards;
    if((num_cards &lt;= 1) || (num_card &gt;= 6)) {
      cout &lt;&lt;&quot;You must have between&quot;
          &lt;&lt;&quot; 2 and 5 cards (inclusive).&quot;;
    }
    else   break;
  }
  return num_cards;
}
</pre>
<p>I think that making <tt class="varname">num_cards</tt> a local
variable is better.</p>
</li>
<li>
<p>I was bothered by the <tt class="function">card_val</tt>
function and when it is used. The function in call inside a
<tt class="literal">for</tt>-loop for each card and it also has a
loop inside the function to check that the input is valid. The
<tt class="literal">for</tt>-loop that calls the function should be
removed. The loop inside the function should be modified to handle
the number of cards sent in. The function should return the total
value for all cards.</p>
<pre class="programlisting">
int card_val(int num_cards){
  char card_val; int value = 0;
  int aces = 0; int card = 1;
  do{
    cout &lt;&lt;&quot;\nEnter value of card number&quot;
        &lt;&lt;card&lt;&lt;&quot;:&quot;;
    cin &gt;&gt; card_value;
    card++;
    switch (tolower(card_val)) { 
    case 'a': 
       value += ace_card(aces);  break;
    case '2': value += 2; break;
&lt;similar cases for 3-9 snipped&gt;
      case 't': value += 10; break;
&lt;similar cases for j, q and k snipped&gt;
      default:
        cout &lt;&lt;&quot;\n Not a valid entry.&quot;
           &lt;&lt;&quot; Please Try again.&quot;;
        card--; break;
      }
    }while(num_cards &gt;= card)
  return value;
}
</pre></li>
<li>
<p>I also notice that the <tt class="varname">aces</tt> variable is
declared locally inside the <tt class="function">card_val</tt>
function. When the number of <tt class="varname">aces</tt> is
calculated the count is lost when <tt class=
"function">card_val</tt> returns. This can be handle two ways, make
<tt class="varname">aces</tt> a global variable and remove the
local inside <tt class="function">card_val</tt> or pass <tt class=
"varname">aces</tt> as <tt class="type">int&amp;</tt> <tt class=
"varname">aces</tt> parameter in <tt class=
"function">card_val</tt>. I will do the second.</p>
<pre class="programlisting">
int card_val(int num_card, int&amp; aces);
</pre></li>
<li>
<p>After looking at the <tt class="literal">if</tt>-statement that
checks the total against the value 21. I think I will rewrite that
code to look simple. I will do all the calculation of the card
value inside <tt class="function">card_val</tt> function and remove
<tt class="varname">new_value</tt> (should be <tt class=
"varname">hand_value</tt> ) function. So the ending of the
<tt class="function">card_val</tt> function will do an extra check
before it returns the total.</p>
<pre class="programlisting">
  while(( value &gt; 21) &amp;&amp; aces &gt;= 1)
    aces--;
    value -= 10;
  }
  return value;
}
</pre>
<p>With the above change I guess statement 3. is not useful. So
keeping aces as a local variable is OK now, but the aces on the
main level should be removed to avoid confusion.</p>
<p>And finally the program could use a few comments.</p>
</li>
</ol>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e1078" id="d0e1078"></a>From: Colin
Hersom <tt class="email">&lt;<a href=
"mailto:colin@hedgehog.cix.co.uk">colin@hedgehog.cix.co.uk</a>&gt;</tt></h3>
</div>
<p>Glancing at this code, my brain says &quot;C&quot;. Looking more closely,
I notice the use of <tt class="classname">cout</tt>, and the
reference parameter in <tt class="function">ace_count</tt>, so this
must be C++. Whilst I have no objection to using C++ as a better C,
I do not think that this code is &quot;better C&quot;: all variables are
declared at the top of functions, rather than where they are first
needed and the <tt class="literal">switch</tt> statement could so
easily be replaced by a better C++ construct, e.g. using <tt class=
"classname">std::map</tt>.</p>
<p>I don't much like the use of &quot;<tt class="literal">using
namespace std</tt>&quot; at the beginning of every file, but since my
compiler effectively does this anyway, I have not means of finding
places where I use a <tt class="literal">std::</tt> item
unqualified, so I shall leave this here.</p>
<p>Let us first tackle the internal design issue: how do we
represent the cards in such a way that the value of the hand can be
calculated when there are aces present. The code presented fails on
this because the aces count inside <tt class=
"function">card_val</tt> is not propagated up to the <tt class=
"function">main</tt> program for passing to <tt class=
"varname">new_value</tt> - which with this code is always going to
see zero aces. We can represent the value of a card or set of cards
by a pair of integers for the value and the ace-count:</p>
<pre class="programlisting">
class card_value {
  int value; int aces;
</pre>
<p>N.B. If you are feeling paranoid about space, we can note that
the value will never exceed 60, so these two members could be
<tt class="type">char</tt> rather than <tt class="type">int</tt>.
Such a choice does not affect the rest of the implementation.</p>
<p>An item of this sort can be initialised in these three ways:</p>
<div class="orderedlist">
<ol type="a">
<li>
<p>no value (for the total)</p>
</li>
<li>
<p>ordinary card</p>
</li>
<li>
<p>ace card</p>
</li>
</ol>
</div>
<p>We can easily make this using one constructor with default
arguments:</p>
<pre class="programlisting">
card_value(int val=0, int ace=0)
      : value(val), aces(ace){}
</pre>
<p>however this would leak the implementation of <tt class=
"varname">aces</tt>, so I prefer to add a helper routine for case
(c) and use the constructor for normal cards only:</p>
<pre class="programlisting">
public:
  card_value(int val=0): value(val), aces(0){}
  static card_value ace();
</pre>
<p>The other constructors and the destructor can be left to the
compiler because the default ones will be correct. I shall return
to the implementation of the <tt class="function">ace()</tt>
function.</p>
<p>We need to add a card to the total, so we need an <tt class=
"literal">operator +=:</tt></p>
<pre class="programlisting">
  card_value &amp;operator+=(const card_value &amp;c){
    value += c.value;
    aces += c.aces;
    return *this;
  }
</pre>
<p>And now the only thing remaining is to calculate the value of
the cards accumulated, so we need an evaluation function:</p>
<pre class="programlisting">
  int hand_value() const;
};
</pre>
<p>&quot;Cheat&quot; I hear you say, &quot;you haven't defined this function.&quot;
Well, yes and no. I can defer the implementation of the function to
be external to the class, but also I have not yet defined how the
value/ace split is made in order to be able to write this function
anyway.</p>
<p>So how am I going to define the <tt class=
"classname">card_value</tt> member variables? I think that it is
clear that non-ace cards have their value as specified in the
original &quot;switch&quot; statement, with <tt class="varname">aces</tt>
being zero. Also <tt class="varname">aces</tt> for an ace needs to
be one, so the problem is the value. I can see three equally valid
values of &quot;value&quot; for an ace card:</p>
<div class="orderedlist">
<ol type="a">
<li>
<p>zero - we add either 1 or 11 in the hand_value function</p>
</li>
<li>
<p>one - this is one possible value, and we add ten if
necessary</p>
</li>
<li>
<p>eleven - this is the other value and we can subtract ten</p>
</li>
</ol>
</div>
<p>I shall choose (b) simply because I want to. Now we can write
the ace and <tt class="function">hand_value</tt> functions:</p>
<pre class="programlisting">
card_value card_value::ace() {
  card_value new_ace(1);
  new_ace.aces = 1;
  return new_ace;
}
int card_value::hand_value() const {
  int total = value;
  int ace_count = aces;
  while (total &lt; 11 &amp;&amp; ace_count &gt; 0) {
// Use up an ace counting as eleven
    total += 10;
    ace_count--;
  }
  return total;
}
</pre>
<p>Now we need to look at how the <tt class=
"classname">card_value</tt> class is going to be used. Firstly,
there must be a declaration of the total value:</p>
<pre class="programlisting">
card_value total;
</pre>
<p>This picks up the constructor with two zero arguments, and so
conveniently initialised to zero. There is a loop, which finds the
card and adds it to the hand.</p>
<pre class="programlisting">
for (...) total += read_card();
</pre>
<p>Here <tt class="function">read_card</tt> will return a
<tt class="classname">card_value</tt>, and so the <tt class=
"function">operator+=</tt> adds it to the hand using the operator
we defined. <tt class="function">read_card</tt> is my replacement
to <tt class="classname">card_val</tt>. This function needs
defining.</p>
<p>I already suggested that the <tt class=
"literal">switch</tt>-statement could be replaced by a <tt class=
"classname">map</tt>, so let us look at this possibility. The
<tt class="classname">map</tt> has to take a character representing
the card and return the <tt class="classname">card_value</tt> for
that card. To save RSI, I like to define a type for the <tt class=
"classname">map</tt>, which also allows possible future
transformation into a class type, if required:</p>
<pre class="programlisting">
typedef std::map&lt;char, card_value&gt; card_map;
</pre>
<p>We are going to need to initialise one of these maps with all
the valid values, so let us define this function:</p>
<pre class="programlisting">
void init_card_map(card_map &amp;cards) {
</pre>
<p>Most of the cards are simple values, and so we can initialise
them with integers, since this uses the <tt class="literal">(val,
ace=0)</tt> constructor:</p>
<pre class="programlisting">
  cards['2'] = 2;
&lt;similar lines snipped&gt;
  cards['t'] = 10;
&lt;similar lines, both upper and lower case snipped&gt;
  cards['K'] = 10;
&lt;/pr</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
