    <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 36</title>
        <link>https://members.accu.org/index.php/journals/840</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 17, #5 - Oct 2005 + 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="https://members.accu.org/index.php/journals/">All</a>

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c94/">175</a>
                    (15)
<br />

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

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

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

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

                    -                        <a href="https://members.accu.org/index.php/journals/c94+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 Competition 36</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 06 October 2005 05:00:00 +01:00 or Thu, 06 October 2005 05:00:00 +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><span class="emphasis"><em>Please note that participation in
this competition is open to all members. The title reflects the
fact that the code used is normally provided by a student as part
of their course work.</em></span></p>
<p><span class="emphasis"><em>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, as are possible
samples.</em></span></p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e30" id="d0e30"></a>Before We
Start</h2>
</div>
<p>Remember that you can get the current problem set in the ACCU
website (<a href="http://www.accu.org/journals/" target=
"_top">http://www.accu.org/journals/</a>). This is aimed at people
living overseas who get the magazine much later than members in the
UK and Europe.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e38" id="d0e38"></a>Student Code
Critique 35 Entries</h2>
</div>
<div class="blockquote">
<blockquote class="blockquote">
<p>Here is a C++ header file with a number of potential problems.
Please critique the code to help the student identify the problems
and to help them to provide some better solutions.</p>
<p>Note: the class <tt class="classname">Report</tt> is not shown.
It contains a large amount of data, which can be explicitly deleted
by a call to <tt class="methodname">ClearAll</tt>.</p>
<pre class="programlisting">
// Reports : vector of reports
class Reports : public map&lt;Data*, Report&gt;
{
public:
  Reports() : nIndex(0) {}
  void ClearAll()
  {
    for (iterator iter=begin();
         iter != end(); iter++)
      (*iter).second.ClearAll();
  }

  Report&amp; GetReport(int nReport)
  {
    int nSize = size();
    assert(nReport &lt; nSize);
    if (nIndex == 0 || nIndex &gt; nReport || 
                    nIndex &gt;=(nSize-1))
    {
      iter = begin();
      nIndex = 0;
    }
 
   for (; iter != end(); iter++, nIndex++)

    {
      if (nIndex == nReport)
        return iter-&gt;second;
    }
    // keep compiler happy
    return *((Report*)0);
  }

protected:
  int      nIndex;
  iterator iter;
};
</pre></blockquote>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e54" id="d0e54"></a>From Simon
Farnsworth <tt class="email">&lt;<a href=
"mailto:accu@farnz.org.uk">accu@farnz.org.uk</a>&gt;</tt></h3>
</div>
<p>Firstly, I should apologise for the poor quality of this
critique. I've only recently started using the STL, so my
understanding is limited. I'm looking forward to seeing and
learning from more expert critiques.</p>
<p>My immediate reaction upon seeing this code was confusion: the
comment says that Reports is a <tt class="classname">vector</tt>,
but the code indicates that it is a <tt class="classname">map</tt>.
While both are containers, <tt class="classname">map</tt> is
associative (in which you reference elements by a key), while
<tt class="classname">vector</tt> elements are referenced by
position. Given the presence of <tt class=
"methodname">GetReport(int nReport)</tt>, I shall assume that the
comment is right, and that the code is an attempt to induce map to
behave like <tt class="classname">vector</tt>.</p>
<p>It is possible that the goal is to have a type that is a
<tt class="classname">map</tt> in some contexts, and a <tt class=
"classname">vector</tt> in others. If this is the case here, the
student would perhaps be better advised to write a container which
includes a <tt class="classname">map</tt> and a <tt class=
"classname">vector</tt> as elements, and provides those operations
on <tt class="classname">map</tt> and <tt class=
"classname">vector</tt> that are needed.</p>
<p>If this was intended as a <tt class="classname">vector</tt>, not
a <tt class="classname">map</tt>, then changing the code to begin:
<tt class="literal">class Reports : public
vector&lt;Report&gt;</tt> removes the need for <tt class=
"methodname">GetReport();</tt> <tt class="classname">vector</tt>
provides <tt class="methodname">operator[]</tt> to retrieve
items.</p>
<p><tt class="methodname">GetReport()</tt> is a mess: it permits
<tt class="varname">nReport</tt> to be negative, but does not
handle this case (<tt class="varname">nReport</tt> should probably
be unsigned, not int). It also relies on the fact that <tt class=
"classname">map</tt> is a sorted associative container to ensure
that a report's number does not change regularly; since there are
no guarantees about the values of the keys used, this could lead to
unexpected behaviour. Finally, it uses casts to trick the compiler
into returning a bad reference. The comment implies that this was
done to silence a compiler warning; in this case, the warning is
generated since <tt class="methodname">GetReport()</tt> can fail to
return a report. However, <tt class="classname">vector</tt>'s
<tt class="methodname">operator[]</tt> will handle this case for
us.</p>
<p>Finally, a couple of style notes: <tt class=
"literal">(*iter)</tt>. is better written as <tt class=
"literal">iter-&gt;</tt>, and preincrement is generally preferred
to postincrement, as the code is slightly simpler (although the
optimizer should fix this for you).</p>
<p>Putting this all together results in the following code:</p>
<pre class="programlisting">
// An exception thrown whenever a requested
// report cannot be found

class NoSuchReport {
    private:
    unsigned report_number;

    public:
    NoSuchReport(unsigned nReport) : 
      report_number(nReport) {}
    unsigned getReport()
    { return report_number; }
    // Compiler can safely autogenerate the 
    // big four.
};

// Reports : vector of reports
class Reports : public vector&lt;Report&gt;
{
    void ClearAll()
    {
        for(iterator iter = begin();
            iter != end(); ++iter)
        {
            iter-&gt;second.ClearAll();
        }
    }
};
</pre>
<p>Should <tt class="methodname">GetReport</tt> be needed for
legacy reasons, it is easy enough to implement as follows:</p>
<pre class="programlisting">
Report &amp;GetReport(unsigned nReport)
{
    return (*this)[nReport];
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e162" id="d0e162"></a>Commentary</h3>
</div>
<p>This code looks relatively innocuous on a first reading, but
repays further thought as there are many problems lurking within
this relatively short piece of code.</p>
<p>To my mind the two most serious problems are (1) the confusion
about whether this class contains a <tt class="classname">map</tt>
or a <tt class="classname">vector</tt> and (2) ownership
issues.</p>
<p>The first criticism concerns access to the objects of the class.
Does <tt class="classname">Reports</tt> represent an array or an
associative container? It may be both, but there is a fundamental
asymmetry about the class as currently coded since all the
associative behaviour comes form inheritance and the array like
behaviour by an additional method. My inclination is to suspect the
inheritance from <tt class="classname">map</tt> and I would prefer
the class to contain a <tt class="classname">map</tt> as member
data and provide methods to manipulate it.</p>
<p>There are several ownership issues. Firstly, the default copy
constructor and copy assignment operator make it possible to copy
the data structure. This is probably not behaviour the writer
expected and is likely to be expensive; as the <tt class=
"classname">map</tt> contains the reports each one will be copied.
There are two standard solutions to this particular issue: either
provide a private definition of these two methods (but no
implementation), or inherit from a non-copyable class such as
<tt class="classname">boost::noncopyable</tt>.</p>
<p>The second ownership issue concerns the member data <tt class=
"varname">nIndex</tt> and <tt class="varname">iter</tt>. These
members seem to be designed to optimise iteration over the elements
of the class by keeping state between successive calls to
<tt class="classname">GetReport</tt> but this is unreliable if the
collection changes between calls to this function. I am also
unhappy that member data like this is made <tt class=
"literal">protected</tt> rather than <tt class=
"literal">private</tt>. If the performance of the iteration
actually is an issue (as determined by some performance
measurements) then a better solution would be to provide an
array-like iterator for the class following the usual STL
pattern.</p>
<p>The third question I have about ownership is the onus seeming to
be on the user of this class to call <tt class=
"methodname">ClearAll()</tt> before the <tt class=
"classname">Reports</tt> object is destroyed. I would prefer this
to be linked to the class's destructor for safety.</p>
<p>The final comment I would wish to raise with the writer of the
code at this point would over the return of a <tt class=
"literal">null</tt> reference when <tt class=
"methodname">GetReport</tt> fails. References never should be null,
and returning one makes the code non-portable and well as
unreliable. It would probably be better to indicate failure by
throwing an exception, perhaps <tt class=
"exceptionname">std::out_of_range</tt>, rather than twisting the
language simply to remove the compiler warning.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e230" id="d0e230"></a>The Winner of
SCC 35</h3>
</div>
<p>The editor's choice is:</p>
<p>Simon Farnsworth</p>
<p>Please email <tt class="email">&lt;<a href=
"mailto:francis@robinton.demon.co.uk">francis@robinton.demon.co.uk</a>&gt;</tt>
to arrange for your prize.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<div>
<h2><a name="d0e242" id="d0e242"></a>Student Code
Critique 36</h2>
</div>
<div>
<h3>(Submissions to <tt class="email">&lt;<a href=
"mailto:scc@accu.org">scc@accu.org</a>&gt;</tt> by Nov 1st)</h3>
</div>
</div>
<p>Here is a C program generating a couple of prime numbers as part
of an exercise on encoding/decoding with public and private keys.
There are two bugs with the program: it produces the same output
each time it is run with one compiler (MSVC) and it loops forever
with another (gcc). Please critique the code to help the student
resolve both these problems with the algorithm. Additionally
suggest any improvements to the coding style and point out any
other issues with the algorithms used. You can also broaden the
critique to include a C++ solution if this may assist the student
with their original task.</p>
<pre class="programlisting">
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
int main()
{

//need to generate number, then find out 
//whether it is a prime, twice.
//then need to generate e and see if it is a
//factor of n.
  int i1, rem1, i2, rem2, i3, rem3, rem4;
  int p, q;
  int n, phi, e;

  //These are the two prime numbers output
  int m, d;

  i1 = 0;
  i2 = 0;
  i3 = 0;
  while(i1!=1)
  {
    p = 100 + 99*rand()/((double)RAND_MAX+1);
    //p is random number between 100 and 200.
    
    i1=p-1;
    rem1 = p%i1;
    
    //find out whether the number is prime
    while(rem1!=0)
    {
      i1--;
      rem1 = p%i1;
    }
  }

  while(i2!=1)
  {
    q = 100 + 99*rand()/((double)RAND_MAX+1);
    i2=q-1;
    rem2 = q%i2;
    while(rem2!=0)
    {
      i2--;
      rem2 = q%i2;
    }
  }

  n = p*q;
  phi = (p-1)*(q-1);
  // phi is the number of primes less than n!
  
  //e picked such that gcd(e, phi) = 1
  while(i3!=1)
  {
    e = phi*rand()/((double)RAND_MAX+1);
    //e is a random number between 0 and phi. 
    
    i3=e;
    rem3 = phi%i3;
    rem4 = 1;

    //this loop finds the highest value of i3 
    //which divides both numbers. It needs to
    // be 1, so they are relatively prime
    while(rem4!=0 )
    { 
      i3--;
      rem3 = phi%i3;
      
      if(rem3==0) 
        rem4 = e%i3;
    }
  }
  
  //the loop will find the value of m such 
  //that e*d mod phi = 1.
  m = 0;
  
  while((e*d)%phi !=1)
  {
    d = (m*phi+1)/e;
    m++;
  };
  printf( &quot;(m,d) is (%i,%i)\n&quot;, m,d );
  return 0; 
}
</pre></div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
