    <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  :: Single Exit</title>
        <link>https://members.accu.org/index.php/articles/338</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #57 - Oct 2003</span></div>

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

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

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

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

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

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

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

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

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+155/">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;Single Exit</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 October 2003 22:56:14 +01:00 or Thu, 02 October 2003 22:56:14 +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>In CVu 15.4 Francis makes a case that some functions are less
complex if they use multiple return statements. In Overload 55 I
stated my preference for single exit via a single return. I'd like
to explore the examples Francis presented to try and explain my
preference more explicitly.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e22" id="d0e22"></a>Example 1 -
Multiple Returns</h2>
</div>
<p>The first code fragment Francis presented was as follows:</p>
<pre class="programlisting">
bool contains(vector&lt;vector&lt;int&gt; &gt;
              const &amp; array, int value) {
  int const rows(array.size());
  int const columns(array[0].size());
  for (int row(0); row != rows; ++row) {
    for (int col(0);
         col != columns;
         ++col) {
      if (array[row][col] == value) {
        return true;
      }
    }
  }
  return false;
}
</pre>
<p>And he wrote:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;if you are a believer that functions should never have more
than a single return you have a problem because however you
reorganise your code the requirement is for two distinct exit
conditions&quot;.</p>
</blockquote>
</div>
<p>I'm a firm believer, but even if I wasn't I'd have to agree that
some multiple returns somehow feel more acceptable than others. And
as Francis says &quot;<span class="quote">perceived complexity is a
function of many things</span>&quot;. However I don't think it's quite
accurate to say the requirement is for two distinct exit
conditions. To try and explain what I mean, consider the following
implementation of <tt class="function">contains</tt><sup>[<a name=
"d0e41" href="#ftn.d0e41" id="d0e41">1</a>]</sup>:</p>
<pre class="programlisting">
bool contains(const vector&lt;vector&lt;int&gt; &gt;
              &amp; array, int value) {
  vector&lt;int&gt; all;
  for (int at = 0; at != array.size();
       ++at) {
    copy(array[at].begin(),
         array[at].end(),
         back_inserter(all));
  }
  return find(all.begin(), all.end(),
              value) != all.end();
}
</pre>
<p>This is an unusual implementation but it does show that the
requirement is always to return a single value to the function
caller (in this case either <tt class="literal">true</tt> or
<tt class="literal">false</tt>). Exactly how you do so depends on
your choice of implementation which is a different matter. Another
approach would be to design an iterator adapter class that
&quot;flattens&quot; the iteration through a container of containers.</p>
<p>Francis continues &quot;<span class="quote">The only ways these can
be combined in a single return statement require either continuing
processing after you know the answer or increasing the perceived
complexity of the code.</span>&quot; Here is the heart of the issue -
the complexity of the code. Is a single-return version of contains
necessarily more complex?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e66" id="d0e66"></a>Example 1 -
Single Return</h2>
</div>
<p>Here's a more realistic single-return version of <tt class=
"function">contains</tt>:</p>
<pre class="programlisting">
bool contains(const vector&lt;vector&lt;int&gt; &gt;
              &amp; values, int value) {
  int at = 0;
  while (at != values.size()
         &amp;&amp; !exists(values[at], value)) {
    ++at;
  }
  return at != values.size();
}
</pre>
<p>This makes use of the following non-standard helper
function:</p>
<pre class="programlisting">
template&lt;typename range, typename value &gt;
         bool exists(const range &amp; all,
  const value &amp; to_find) {
    return find(all.begin(), all.end(),
                to_find) != all.end();
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e80" id="d0e80"></a>Example 1 -
Comparison</h2>
</div>
<p>What are the differences between these single/multiple return
versions?</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="bold"><b>Line count.</b></span> No difference. (I
haven't counted lines containing a single left/right brace).</p>
</li>
<li>
<p><span class="bold"><b>Maximum indent.</b></span> The deepest
control in the multiple-return version is 3 - the return in an
<tt class="literal">if</tt> in a <tt class="literal">for</tt> in a
<tt class="literal">for</tt> whereas the deepest control in the
single-return version is 1 - the increment in the <tt class=
"literal">while</tt>. This is the reason the single-return version
needs fewer lines containing a single left/right brace.</p>
</li>
<li>
<p><span class="bold"><b>Function count.</b></span> The
multiple-return version is a single function whereas the
single-return version uses a helper function. The helper function
is useful in its own right and could quite conceivably have already
existed. Small helper functions are significant because they can
help to make other functions smaller and clearer.</p>
</li>
<li>
<p><span class="bold"><b>Loop scaffolding complexity.</b></span> By
using the helper function the single-return version has lost a
whole level of iteration scaffolding.</p>
</li>
<li>
<p><span class="bold"><b>Return expression complexity.</b></span>
The multiple-return version uses two literals, <tt class=
"literal">true</tt> and <tt class="literal">false</tt>. One of
these returns occurs at indentation level 3. In contrast the
single-return version uses a single boolean expression at
indentation level 1.</p>
</li>
<li>
<p><span class="bold"><b>Loop condition complexity.</b></span> The
multiple-return version has two very simple (and very similar)
boolean expressions as its two <tt class="literal">for</tt>
statement continuation conditions. The single-return version has
one (more complex) boolean expression in its <tt class=
"literal">while</tt> statement continuation condition. How
comfortable you are with this more complex boolean expression
(using the <tt class="literal">&amp;&amp;</tt> short-circuiting
operator) is largely a matter of how familiar you are with this
style.</p>
</li>
<li>
<p><span class="bold"><b>Style.</b></span> If you are looking for
an element in a C++ vector you could argue that it's reasonable to
expect to use the C++ find algorithm, as the multiple-return
version does. In contrast the single-return version uses a more
C-like explicit subscript iteration. The difference is quite subtle
in this case but it does serve to highlight an important point
Francis made - &quot;<span class="quote">perceived complexity is a
function of many things (one of them being the individual
reader)</span>&quot;. I think its fair to say the more experience you
have of &quot;mature&quot; C++/STL style the more readable you'd find the
single-return version.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e151" id="d0e151"></a>Example 2 -
Multiple Returns</h2>
</div>
<p>The second code fragment Francis presented is as follows (some
code elided, I assume the <tt class="literal">int &lt;-&gt;
bool</tt> conversions are deliberate):</p>
<pre class="programlisting">
bool will_be_alive(life_universe
                       const &amp; data,
                   int i,
                   int j) {
  int const diagonal_neighbours = ...;
  int const orthogonal_neighbours = ...;
  int const live_neighbours =
              diagonal_neighbours +
              orthogonal_neighbours;
  if (live_neighbours == 3)
    return true;
  if (live_neighbours == 2)
    return data[i][j];
  return false;
}
</pre>
<p>I would start by rewriting this as follows:</p>
<pre class="programlisting">
bool will_be_alive(const life_universe &amp; data,
                   int i,
                   int j) {
  const int diagonal_neighbours = ...;
  const int orthogonal_neighbours = ...;

  const int live_neighbours =
                diagonal_neighbours +
                orthogonal_neighbours;
  if (live_neighbours == 3)
    return true;
  else if (live_neighbours == 2)
    return data[i][j];
  else
    return false;
}
</pre>
<p>The difference is the explicit coding of the control-flow
surrounding the return statements. Do you think making the
control-flow explicit is a good thing? If you're not that bothered
I invite you to consider the following:</p>
<pre class="programlisting">
if (live_neighbours == 3)
return true;
</pre>
<p>I hope you're more concerned by this lack of indentation. These
days indenting your code to reflect logical grouping is taken as an
article of faith that people forget to question or recall exactly
why it is used. Indentation visibly groups similar actions and
decisions occurring at the same level. If you believe that
indentation is a Good Thing there is a strong case for <span class=
"emphasis"><em>clearly</em></span> and explicitly emphasising that
all three return statements exist at the same level. In contrast,
and significantly, the multiple-returns in the first example are
not at the same level.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e175" id="d0e175"></a>Example 2 -
Single Return</h2>
</div>
<p>Francis also presented example 2 using a single return involving
nested ternary operators:</p>
<pre class="programlisting">
return (live_neighbours == 3)
  ? true
  : (live_neighbours == 2)
    ? data[i][j]
    : false;
</pre>
<p>I agree with Francis that this adds nothing in terms of clarity.
In fact I think it's a big minus. This is the kind of code that
gives the ternary operator a bad name. But inside this long and
inelegant statement there is a shorter and more elegant one trying
to get out. To help it escape consider a small progression. We
start with this (not uncommon) pattern:</p>
<pre class="programlisting">
bool result;
if (expression)
  result = true;
else
  result = false;
return result;
</pre>
<p>This is exactly the kind of code that gives single-exit a bad
name. It is overly verbose; it isn't a simple, clear, and direct
expression of its hidden logic. It is better as:</p>
<pre class="programlisting">
if (expression)
  return true;
else
  return false;
</pre>
<p>But this is still overly verbose. So we take a short step
to:</p>
<pre class="programlisting">
return (expression) ? true : false;
</pre>
<p>And removing the last bit of duplication we finally arrive
at:</p>
<pre class="programlisting">
return expression;
</pre>
<p>This is not better merely because it is shorter. It is better
because it is a more direct expression of the problem. It has been
stripped of its solution focused temporary variable, its <tt class=
"literal">if-else</tt>, and its assignments; all that remains is
the problem focused expression of the answer. It has less code and
more software. Applying the same process to the chained <tt class=
"literal">if-else</tt> containing three return statements we arrive
not at a nested ternary operator but at this:</p>
<pre class="programlisting">
return live_neighbours == 3 ||
       live_neighbours == 2 &amp;&amp;
       data[i][j];
</pre>
<p>This is focused on and is a direct expression of the problem in
exactly the same way.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e210" id=
"d0e210"></a>Conclusion</h2>
</div>
<p>My rules of thumb are as follows:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Almost all functions are better with a single return. The issue
is separation of concerns. Do you separate out the statements that
determine the answer from the statement/s that return the answer?
Multiple-return versions don't whereas single-return versions
do.</p>
</li>
<li>
<p>Multiple return statements become less acceptable the further
apart they become (both in terms of logical indentation and
physical line number). Large functions have greater scope for abuse
simply because they allow multiple returns to live farther
apart.</p>
</li>
<li>
<p>Multiple return statements are more acceptable when they are all
at the same level of a mutually-exclusive selection. In most cases
these multiple returns can be refactored into a more expressive
single return.</p>
</li>
</ul>
</div>
<p>But remember, dogmatically following rules is not a recipe for
good software. The best software flows from programmers who think
about what they do and who follow principles and practices that
naturally generate quality.</p>
<p>Many thanks to Kevlin for an insightful review of a first draft
of this article.</p>
</div>
<div class="footnotes"><br>
<hr class="c2" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e41" href="#d0e41" id=
"ftn.d0e41">1</a>]</sup> The array[at] duplication can be avoided
like this:</p>
<pre class="programlisting">
copy(array[at], back_inserter(all));
</pre>
<p>which uses a handy (but sadly non-standard) version of copy
which, coincidentally, I also used in my other article (Software As
Read).</p>
<pre class="programlisting">
template&lt;typename range, typename output&gt;
output copy(const range &amp; source,
            output sink) {
  return copy(source.begin(), source.end(),
              sink);
}
</pre></div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
