    <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  :: Everyday Coding Habits for Safety and Simplicity</title>
        <link>https://members.accu.org/index.php/journals/2521</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 30, #3 - July 2018 + Programming Topics</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/c387/">303</a>
                    (9)
<br />

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

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

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

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

                    -                        <a href="https://members.accu.org/index.php/journals/c387+65/">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;Everyday Coding Habits for Safety and Simplicity</h1>
<p><strong>Author:</strong>&nbsp;Bob Schmidt</p>
<p>
<strong>Date:</strong> 05 July 2018 16:54:46 +01:00 or Thu, 05 July 2018 16:54:46 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Arun Saha has some simple advice for forming good habits in C++.</p>
<p><strong>Body:</strong>&nbsp;<p>A habit is a choice that we deliberately make at some point, and then stop thinking about, but continue doing, often every day <a href="#[1]">[1]</a>.</p>

<p>A lot of times, minor differences in code can lead to significantly better code. In this article, let us go together through a few such cases which we encounter in our everyday coding life. None of these is revolutionary (in fact, you may have seen them before); rather this is a collection of suggestions how small changes â€“ a few characters in most cases â€“ can make big differences. [The examples in this article are in C++; a lot of them apply in C as well.]</p>

<h2>Always initialize automatic variables</h2>

<p>Do not define uninitialized variables. For example, donâ€™t do this:</p>

<pre class="programlisting">
  int result;</pre>
  
<p>This defines the variable but it is not initialized to any known value. (It will have an indeterminate value.) I have seen a lot of bugs arise for this reason alone. Often such bugs stay hidden for a long time and express themselves one fine morning. For example, this may happen when the compiler or the compiler version is changed.</p>

<p>Instead, initialize it to some known value:</p>

<pre class="programlisting">
  int result = 0;</pre>
  
<p>The exact value to be initialized is not important; choose something that is appropriate to the context.</p>

<p>Note that this is different from accessing (reading) uninitialized variables (which can be detected by the compiler warning option <code>-Wuninitialized</code>). Here, the recommendation is to never leave a defined variable uninitialized, even if it is not being accessed.</p>

<p>As you might have realized, this applies only to <em>automatic</em> (or local) variables of the primitive types like <code>char</code>, <code>int</code>, <code>double</code> with all possible signedness and width, <code>float</code>, and <code>bool</code>. If <code>T</code> is a type with sane default constructor (such as <code>std::string</code>), then</p>

<pre class="programlisting">
  T result;</pre>
  
<p>is not a problem.</p>

<p>One of the reasons for this behavior is that the primitive types do not have constructors. Despite that, a compiler may choose to emit an instruction for â€˜zeroâ€™ initialization. However, with C++ and C compilers â€“ together with their users â€“ being very performance sensitive, such (initialization) instructions are not usually emitted since they are not required by the standard. </p>

<p>[Would it make sense for compilers to provide a knob such as <code>-fzero-initialize-primitives</code>?]</p>


<h2>Prefer defining variables only when needed</h2>

<p>Donâ€™t define a variable too early only to assign it later. For example, donâ€™t do this:</p>

<pre class="programlisting">
  int result = 0;
  // many
  // intermediate
  // lines
  result = ComputeSomething(input);</pre>
  
<p>Rather, define and initialize it together at the point it is used.</p>

<pre class="programlisting">
  int result = ComputeSomething(input);</pre>
  
<p>If the variable is not expected to be modified thereafter, then mark it constant as:</p>

<pre class="programlisting">
  int const result = ComputeSomething(input);</pre>
  
<p>In fact, try organizing the flow of logic and code such that it is a series of <code>const</code> variables. It not only prevents inadvertent modification of the variable, it also makes it easy for a reader to follow the flow; it will be one less thing to track in her working memory. It is considered that the number of objects that a human can hold in working memory is 7 Â± 2 <a href="#[2]">[2]</a>. I try to be safe and be on the lower side!</p>


<h2>Prefer input arguments to be immutable</h2>

<p>The safety argument applies to function arguments too. Prefer making the function arguments <code>const</code> as much as possible. If the method is just reading the data without modifying, then the data must be <code>const</code>. So, instead of</p>

<pre class="programlisting">
  void PrintInorderTraversal(TreeNode * root);</pre>
  
<p>prefer</p>

<pre class="programlisting">  // Declaration in .h
  void PrintInorderTraversal(
    TreeNode const * root);</pre>
	
<p>I recommend going one step further by marking the input variable <code>const</code>. This can be done in the implementation file without putting it in the header file. This <code>const</code> prevents the local variable pointing to the data from accidentally getting modified and starting to point to different data.</p>

<pre class="programlisting">  // Definition in .cc
  void PrintInorderTraversal(
    TreeNode const * const root);</pre>
	
<p>The recommendation applies equally well for pass-by-reference arguments. There, instead of</p>

<pre class="programlisting">
  bool IsValidIpAddress(std::string&amp; input);</pre>
  
<p>prefer</p>

<pre class="programlisting">
  bool IsValidIpAddress(std::string const&amp; input);</pre>

<h2>Accessor member functions must be const</h2>

<p>In C++, member functions can be <code>const</code> when they are not modifying the object. Prefer making the member functions <code>const</code> whenever possible. For example, if a method, such as <code>Print()</code>, is not modifying the object, then instead of</p>

<pre class="programlisting">
  struct Foo {
    &lt;stuff&gt;
    void Print();
    &lt;more stuff&gt;
  };</pre>
  
<p>prefer writing it as</p>

<pre class="programlisting">
  struct Foo {
    &lt;stuff&gt;
    void Print() const;  // Note: 'const'

    &lt;more stuff&gt;
  };</pre>
  
<p>As you know, if a member variable is marked <code>mutable</code>, then even a <code>const</code> qualified method can modify it. A mutable variable is appropriate only in some specific circumstances (e.g. a mutex, a hit counter); donâ€™t overuse it.</p>


<h2>Prefer default member initialization</h2>

<p>Member variables of primitive types are initialized in the constructor. Usually, the constructor is in a different file and there is potential for the initialization to be missed. This tends to happen less during initial creation but more during later enhancements and maintenance. To prevent that, do not defer the initialization until the constructor; instead, prefer to initialize them inline in the class body.</p>

<p>Consider the following snippet.</p>

<pre class="programlisting">  // .h file
  struct Foo {
    explicit Foo(int64_t);
    &lt;stuff&gt;
    int64_t fooId_; // Initialization deferred to 

                    // ctor Potential to be missed
  }

  // .cc file
  Foo::Foo(int64_t fooId) : fooId_{fooId} {}</pre>
  
<p>For safety, I recommend writing it as the following using the default member initialization feature <a href="#[3]">[3]</a>.</p>

<pre class="programlisting">
  struct Foo {
    &lt;stuff&gt;
    int64_t fooId_{0}; // Known initialization if

                       // missed in .cc constructor
  }
  Foo::Foo(int64_t fooId) : fooId_{fooId} {}</pre>
  
<p>Except for a few types like bit-fields and non-length-specified arrays, this can be used for most of the data types. Note that, if a member variable has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.</p>

<p>You may have noticed that the concept here is similar to an item above except that the variable type is different: automatic variable vs. member variable. In both cases, the motivation is to ensure that a variable is always initialized to a known value. Instances of such missing initializations may be detected by g++ with the warning option <code>-Weffc++</code> <a href="#[4]">[4]</a>.</p>


<h2>Prefer immutable member variables if you can</h2>

<p>For class members which are initialized at construction and never change during the lifetime of the object, prefer marking them const. Consider the following example where the object carries the time instant when it was constructed.</p>

<pre class="programlisting">
  using TimePoint = std::chrono::time_point
    &lt;std::chrono::system_clock&gt;;
  inline TimePoint
  GetTimePointNow() {
    return std::chrono::system_clock::now();
  }</pre>
  
<p>Instead of the following</p>

<pre class="programlisting">  // .h file
  struct Foo {
    &lt;stuff&gt;
    int64_t   fooId_{0};
    TimePoint  creationInstant_;
  }
  // .cc file
  Foo::Foo(int64_t fooId) :
    fooId_{fooId},
    creationInstant_{GetTimePointNow()} {}</pre>
	
<p>prefer doing</p>

<pre class="programlisting">
  // .h file
  struct Foo {
    &lt;stuff&gt;
    int64_t const   fooId_{0};
    TimePoint const creationInstant_; // Note const

  }</pre>
  
<p>The motivation is similar to marking automatic variables <code>const</code>; safety from accidental modification and reduced burden of information tracking.</p>


<h2>Prefer APIs to provide the result as a return value</h2>

<p>Donâ€™t design an API to update a reference or a pointer to the result, let it <em>return</em> the result. For example, instead of doing</p>

<pre class="programlisting">
  int result = 0;
  ComputeResult(n, result);   // pass by reference
</pre>

<p>or</p>

<pre class="programlisting">
  int result = 0;
  ComputeResult(n, &amp;result);  // pass by pointer
</pre>

<p>prefer doing</p>

<pre class="programlisting">
  int const result = ComputeSomething(n);</pre>
  
<p>This style allows the returned value to be saved in a <code>const</code> variable and to be used in the subsequent computation. This certainly applies to objects that are trivially copyable, such as the primitive types. For objects that are not trivially copyable, it can still be applicable thanks to:</p>

<ol>
	<li>Return Value Optimization (RVO)</li>
	<li>Copy Elision</li>
	<li>Move semantics</li>
</ol>

<p>Note however that the rules of the above are quite involved and, in certain situations, they may not kick in. So, if you want to play safe and avoid it for non-trivially copyable types, thatâ€™s understandable.</p>


<h2>Prefer for-loops over while-loops</h2>

<p>Instead of writing as a <code>while</code> loop, prefer writing loops as <code>for</code> loops whenever possible. This is not just a bias towards one keyword over another; this enables easier comprehension of loop invariants. For example, instead of the following</p>

<pre class="programlisting">
  int i = 0;
  while (i &lt; n) {
    &lt;possibly multiple lines of loop body&gt;
    i++;
  }</pre>
  
<p>prefer writing it as</p>

<pre class="programlisting">
  for (int i = 0; i &lt; n: ++i) {
    &lt;loop body&gt;
  }</pre>
  
<p>In addition, this style has another advantage: the loop variable (here, <code>i</code>) is not â€˜leakedâ€™ to the outer scope <em>unnecessarily</em>.</p>

<p>The recommendation goes for linked list traversal too. Here, instead of</p>

<pre class="programlisting">
  ListNode const * curr = head;
  while (curr) {
    &lt;possibly multiple lines of loop body&gt;
    curr = curr-&gt;next;
  }</pre>
  
<p>prefer writing it as</p>

<pre class="programlisting">
  for (ListNode const * curr = head; curr; 
    curr = curr-&gt;next) {
    &lt;loop body&gt;
  }</pre>
  
<p>As if the above is not enough, the above applies to traversing from both ends. So, instead of</p>

<pre class="programlisting">
  void Reverse(T * arr, int64_t const n) {
  int64_t left = 0;
    int64_t right = n - 1;
    while (left &lt; right) {
      swap(arr[left], arr[right]);
      left++;
      right--;
    }
  }</pre>
  
<p>prefer writing it as</p>

<pre class="programlisting">
  void Reverse(T * arr, int64_t const n) {
    for (int64_t left = 0, right = n - 1;
    left &lt; right; ++left, --right) {
      swap(arr[left], arr[right]);
    }
  }</pre>
  
<p>Note that although it is a by product, saving the number of lines is not the objective.</p>


<h2>Prefer combining boolean conditions into a well-named variable</h2>

<p>If the program logic requires evaluating multiple conditions, then instead of clamping them together in the conditional of an <code>if</code> statement, for example, instead of</p>

<pre class="programlisting">
  if (someCondition(input) &amp;&amp;
    anotherCondition(input) &amp;&amp;
    !yetAnotherCondition(input)) {
      &lt;body&gt;</pre>
	  
<p>prefer</p>

<pre class="programlisting">
  bool const input_valid = someCondition(input) &amp;&amp;
    anotherCondition(input) &amp;&amp;
    !yetAnotherCondition(input);
  if (input_valid) {
    &lt;body&gt;</pre>
	
<p>This has two benefits: the evaluated condition gets a human-readable name and it becomes easier to view what the condition evaluated to (i.e. true or false) using a log message or a debugger.</p>

<h2>Prefer separate asserts for separate conditions</h2>

<p>If you use asserts in your source code to validate assumptions, then do not combine multiple conditions into a single <code>assert</code> statement.</p>

<pre class="programlisting">
  void Copy(char * dst, char const * src, 
    size_t const length) {
      assert(dst &amp;&amp; src); // 2 conditions combined

    &lt;continued&gt;</pre>
	
<p>If you do so and the assertion fails, then the generated message would mention that the combined condition has failed (along with some meta information like filename and line number). The person who has to debug the problem (it could be you at a future time) would not be clear exactly why the assertion failed. Instead, break the single assertion into multiple simpler assertions.</p>

<pre class="programlisting">
  void Copy(char * dst, char const * src, 
    size_t const length) {
      assert(dst);
      assert(src);
      &lt;continued&gt;</pre>
	  
<p>Now, if the assertion fails, it would be obvious what exactly has failed!</p>

<h2>Summary</h2>

<p>The table below provides an at-a-glance view of the above recommendations.</p>

<table>
	<tr>
		<th></th>
		<th>Avoid doing</th>
		<th>Prefer doing</th>
	</tr>
	
	<tr>
		<td>1</td>
		<td><pre class="programlisting">
int result;</pre></td>
		<td><pre class="programlisting">
int result = 0;</pre></td>
	</tr>
	
	<tr>
		<td>2</td>
		<td><pre class="programlisting">
int result = 0;int
result = ComputeSomething(input);</pre></td>
		<td><pre class="programlisting">
int const result =
ComputeSomething(input);</pre></td>
	</tr>
	
	<tr>
		<td>3</td>
		<td><pre class="programlisting">
void PrintInorderTraversal(
   TreeNode * root);
bool IsValidIpAddress(
   std::string&amp; input);</pre></td>
		<td><pre class="programlisting">
void PrintInorderTraversal(
   TreeNode const * const root);
bool IsValidIpAddress(
   std::string const&amp; input);</pre></td>
	</tr>
	
	<tr>
		<td>4</td>
		<td><pre class="programlisting">
void Foo::Print();</pre></td>
		<td><pre class="programlisting">
void Foo::Print() const;</pre></td>
	</tr>
	
	<tr>
		<td>5</td>
		<td><pre class="programlisting">
int64_t fooId_;</pre></td>
		<td><pre class="programlisting">
int64_t fooId_{0};</pre></td>
	</tr>
	
	<tr>
		<td>6</td>
		<td><pre class="programlisting">
TimePoint creationInstant_;</pre></td>
		<td><pre class="programlisting">
TimePoint creationInstant_;</pre></td>
	</tr>
	
	<tr>
		<td>7</td>
		<td><pre class="programlisting">
ComputeResult(n, &amp;result);</pre></td>
		<td><pre class="programlisting">
int const result = ComputeSomething(n);</pre></td>
	</tr>
	
	<tr>
		<td>8</td>
		<td><pre class="programlisting">
int i = 0;
while (i &lt; n) {
  &lt;loop body&gt;
  i++;
}</pre></td>
		<td><pre class="programlisting">
for (int i = 0; i &lt; n: ++i) {
  &lt;loop body&gt;
}</pre></td>
	</tr>
	
	<tr>
		<td>9</td>
		<td><pre class="programlisting">
if (someCondition(input) &amp;&amp;
  anotherCondition(input) &amp;&amp;
  !yetAnotherCondition(input)) {</pre></td>
		<td><pre class="programlisting">
bool const input_valid =
   someCondition(input) &amp;&amp;
   anotherCondition(input) &amp;&amp;
   !yetAnotherCondition(input);

if (input_valid) {</pre></td>
	</tr>
	
	<tr>
		<td>10</td>
		<td><pre class="programlisting">
assert(dst &amp;&amp; src);</pre></td>
		<td><pre class="programlisting">
assert(dst);
assert(src);</pre></td>
	</tr>
</table>

<p>Software engineering is an eternal fight with complexity. The recommendations here are based on my experience as a software engineer. Over time, I have found them useful in constructing durable code. Unless your situation precludes, I recommend trying them out. Once they become a habit <a href="#[1]">[1]</a>, you would cease thinking about them and focus on other important aspects of your code.</p>

<h2>References</h2>

<p class="bibliomixed"><a id="[1]"></a>[1]	<a href="http://charlesduhigg.com/how-habits-work/">http://charlesduhigg.com/how-habits-work/</a></p>

<p class="bibliomixed"><a id="[2]"></a>[2]	<a href="https://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two">https://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two</a></p>

<p class="bibliomixed"><a id="[3]"></a>[3]	<a href="https://en.cppreference.com/w/cpp/language/data_members">https://en.cppreference.com/w/cpp/language/data_members</a></p>

<p class="bibliomixed"><a id="[4]"></a>[4]	<a href="https://stackoverflow.com/questions/2099692/easy-way-find-uninitialized-member-variables">https://stackoverflow.com/questions/2099692/easy-way-find-uninitialized-member-variables</a></p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
