    <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  :: Living Within Constraints</title>
        <link>https://members.accu.org/index.php/articles/2398</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 + CVu Journal Vol 29, #3 - July 2017</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/c77/">CVu</a>

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

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+375/">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;Living Within Constraints</h1>
<p><strong>Author:</strong>&nbsp;Bob Schmidt</p>
<p>
<strong>Date:</strong> 07 July 2017 18:04:54 +01:00 or Fri, 07 July 2017 18:04:54 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Pete Goodliffe constrains whatâ€™s possible in your code.</p>
<p><strong>Body:</strong>&nbsp;<p>We have already considered defensive programming techniques (in <em>CVu</em> 29.1) to help make your code better. These techniques force you to consider what might go wrong â€“ to assume the worst. So how can we physically incorporate these assumptions into our software so theyâ€™re not elusive problems waiting to emerge? Clearly, we can simply write a little extra code to check for each condition. In doing so, weâ€™re codifying the <em>constraints</em> on program functionality and behaviour.</p>


<h2>Constraints</h2>

<p>The most obvious implementation of constraint checking in C and C++ is the humble <code>assert</code>. Weâ€™ll look at it in detail later, but itâ€™s simple to use:</p>

<pre class="programlisting">
  assert(itemIndex &lt; maxNumItems);</pre>
  
<p>When running a program with assertions enabled (usually this has to be within a â€˜debugâ€™ configuration build) a failure to satisfy the assertion will force the program to <em>unceremoniously</em> stop. Immediately. The program will dump out some diagnostic information about the assertion failure. But it will do so in an ugly way the programmer will understand. Itâ€™s definitely not a nice user experience!</p>

<p><code>assert</code> is simple, but can sometimes be a sledgehammer used to crack a walnut. Thereâ€™s no subtly; you cannot control what it does (apart from switch it on or off).</p>

<p>In a mature system, what <em>do</em> we want the program to do if a constraint is broken?</p>

<p>Since this kind of constraint will likely be more than a simple detectable and correctable run-time error, it must be a flaw in the program logic. There are few possibilities for the programâ€™s reaction:</p>

<ul>
	<li>Turn a blind eye to the problem, and hope that nothing will go wrong as a consequence.</li>
	
	<li>Give it an on-the-spot fine and allow the program to continue (e.g., print a diagnostic warning or log the error).</li>
	
	<li>Go directly to jail; do not pass go (e.g., abort the program immediately, in a controlled or uncontrolled manner â€“ either allowing it to neatly clean up if possible, or just exiting like assert).</li>
</ul>

<p>Indeed, you may have different types of constraint condition that require different ways of handing.</p>

<p>For example, it is invalid to call Câ€™s <code>strlen</code> function with a string pointer set to zero, because the pointer will be immediately dereferenced, so the latter two options are the most plausible. Itâ€™s probably most appropriate to abort the program immediately, since dereferencing a null pointer can lead to all sorts of catastrophes on unprotected operating systems.</p>

<p>Checking a value is â€˜saneâ€™ before displaying it on the screen might not need such a brute force approach.</p>

<p>Many debug/logging libraries provide constraint checking services. Generally they are configurable and flexible. Constraint checking is often bound in logging libraries because often you want to log a broken constraint, but allow the application to continue nevertheless.</p>

<h3>How to use constraints</h3>

<p>There are a number of different scenarios in which constraints are used:</p>

<ul>
	<li><strong>Preconditions</strong> These are conditions that must hold true <em>before</em> a section of code is entered. If a precondition fails, itâ€™s due to a fault in the client code.</li>
	
	<li><strong>Postconditions</strong> These must hold true <em>after</em> a code block is left. If a postcondition fails, itâ€™s due to a fault in the supplier code.</li>
	
	<li><strong>Invariants</strong> These are conditions that hold true every time the programâ€™s execution reaches a particular point: between loop passes, across method calls, and so on. Failure of an invariant implies a fault in the program logic.</li>
	
	<li><strong>Assertions </strong>Any other statement about a programâ€™s state at a given point in time.</li>
</ul>

<p>The first two are frustrating to implement without language support â€“ if a function has multiple exit points, then inserting a postcondition gets messy. Eiffel supports pre- and postconditions in the core language and can also ensure that constraint checks donâ€™t have any side effects.</p>

<p>Good constraints expressed in code make your program clearer and more maintainable. This technique is also known as <em>design by contract</em>, since constraints form an immutable contract between sections of code.</p>

<p>Without built-in language-level constraint checking, the code mechanism used to check each of type of constraint is usually identical, and the type of constraint is just implicit from its location in the code.</p>

<h3>What to constrain</h3>

<p>There are a number of different problems you can guard against with constraints. For example, you can:</p>

<ul>
	<li>Check all array accesses are within bounds.</li>
	<li>Assert that pointers are not zero before dereferencing them.</li>
	<li>Ensure that function parameters are valid.</li>
	<li>Sanity check function results before returning them.</li>
	<li>Prove that an objectâ€™s state is consistent before operating on it.</li>
	<li>Guard any place in the code where youâ€™d write the comment <em>We should never get here</em>.</li>
</ul>

<p>The first two of these examples are particularly C/C++ focused. Other languages have their own ways of avoiding some of these pitfalls.</p>

<p>Just how much constraint checking should you do? Placing a check on every other line is a bit extreme. As with many things, the correct balance becomes clear as the programmer gets more mature. Is it better to have too much or too little? It is possible for too many constraint checks to obscure the codeâ€™s logic. Readability is the best single criterion of program quality: If a program is easy to read, it is probably a good program; if it is hard to read, it probably isnâ€™t good.</p>

<p>Realistically, putting pre- and postconditions in major functions plus invariants in the key loops is sufficient.</p>

<h3>Removing constraints</h3>

<p>This kind of constraint checking is usually only required during the development and debugging stages of program construction. Once we have used the constraints to convince ourselves (rightly or wrongly) that the program logic is correct, we would ideally remove them so as not to incur an unnecessary runtime overhead.</p>

<p>Thanks to the wonders of modern technology, all of this is perfectly possible. As weâ€™ve already seen, the C and C++ standard libraries provide a common mechanism to implement constraints â€“ <code>assert</code>. <code>assert</code> acts as a procedural firewall, testing the logic of its argument. It is provided as an alarm for the developer to show incorrect program behaviour and should not be allowed to trigger in customer-facing code. If the assertionâ€™s constraint is satisfied execution continues. Otherwise, the program aborts, producing an error message looking something like this:</p>

<pre class="programlisting">
  bugged.cpp:10: int main(): Assertion &quot;1 == 0&quot;  failed.</pre>
  
<p><code>assert</code> is implemented as a preprocessor macro, which means it sits more naturally in C than in C++. There are a number of more C++-sympathetic assertion libraries available.</p>

<p>To use <code>assert</code> you must <code>#include &lt;assert.h&gt;</code>. You can then write something like <code>assert(ptr != 0);</code> in your function. Preprocessor magic allows us to strip out assertions in a production build by specifying the <code>NDEBUG</code> flag to the compiler. All <code>assert</code>s will be removed, and their arguments will not be evaluated. This means that in production builds <code>assert</code>s have no overhead at all.</p>

<p>Whether or not assertions <em>should</em> be completely removed, as opposed to just being made non fatal, is a debatable issue. There is a school of thought that says after you remove them, you are testing a <em>completely different</em> piece of code. Others say that the overhead of assertions is not acceptable in a release build, so they must be eliminated. (But how often do people profile execution to prove this?)</p>

<p>Either way, our assertions must not have any side effects. What would happen, for example, if you mistakenly wrote:</p>

<pre class="programlisting">
  int i = pullNumberFromThinAir();
  assert(i = 6); // hmm - should type more
                 // carefully!

  printf(&quot;i is %d\n&quot;, i);</pre>
  
<p>The assertion will never trigger in a debug build; its value is 6 (near enough <em>true</em> for C). However, in a release build, the <code>assert</code> line will be removed completely and the <code>printf</code> will produce different output. This can be the cause of subtle problems late in product development. Itâ€™s quite hard to guard against bugs in the bug-checking code!</p>

<p>Itâ€™s not difficult to envision situations where assertions might have  more subtle side effects. For example, if you <code>assert(invariants());</code>, yet the <code>invariants()</code> function has a side effect, itâ€™s not easy to spot.</p>

<p>Since assertions can be removed in production code, it is vital that only constraint testing is done with <code>assert</code>. Real error condition testing, like memory allocation failure or file system problems, should be dealt with in ordinary code. You wouldnâ€™t want to compile that out of your program! Justifiable run-time errors (no matter how undesirable) should be detected with defensive code that can never be removed.</p>

<p>Java has a similar <code>assert</code> mechanism, which throws an exception (<code>java.lang.AssertionError</code>) instead of causing a program abort. .NET provides an assertion mechanism in the frameworkâ€™s <code>Debug</code> class.</p>

<p>When you discover and fix a fault, it is good practice to slip in an assertion where the fault was fixed. Then you can ensure that you wonâ€™t be bitten twice. If nothing else, this would act as a warning sign to people maintaining the code in the future.</p>

<p>A common C++/Java technique for writing class constraints is to add a single member function called <code>bool invariant()</code> to each class. (Naturally this function should have no side effects.) Now an <code>assert</code> can be put at the beginning and end of each member function calling this invariant. (There should be no assertion at the beginning of a constructor or at the end of the destructor, for obvious reasons.) For example, a <code>circle</code> class invariant may check that <code>radius != 0</code>; that would be invalid object state and could cause later calculations to fail (perhaps with a divide by zero error).</p>

<h2>Questions</h2>

<ul>
	<li>How much constraint checking do you employ in your codebase?</li>
	<li>Are there some functions that benefit more from pre/post condition checking? Why?</li>
	<li>How can you ensure that the logic in a constraint expression will have no observable affect on the programâ€™s behaviour?</li>
</ul>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
