Title: Avoiding the break statement
Slug: avoiding-the-break-statement
Date: 2009-11-25 16:01:00
Author: Kartones
Lang: en
Tags: Development, Patterns & Practices, C#
Description: Avoiding the break statement in coding by using additional checks in the loop's condition expression for better readability and avoiding messy code.

 <p>Some coding guidelines and best practices advice against the use of <font face="Courier New">continue</font> and <font face="Courier New">break</font> statements.</p>  <p>With <font face="Courier New">continue</font> the solution is easy, placing an <font face="Courier New">if</font> (or if it existed to call <font face="Courier New">continue</font>, negate it to execute the code).</p>  <p>But with <font face="Courier New">break</font>, it is not always so easy. Some times, in fact the resulting code is more messed up or harder to read (usually because of too much ifs), so I use <font face="Courier New">break</font> sometimes in my code if avoiding it is going to be worse for readability.</p>  <p>The most common case of using the <font face="Courier New">break</font> statement is looping through an indexed array of elements searching for something:</p>  <p><font face="Courier New">int[] numbers = { 1, 2, 3, 4, 5 }</font><font face="Courier New">;        <br>for (int index = 0; index &lt; numbers.Length; </font><font face="Courier New">index++)      <br>{  <br></font><font face="Courier New">    if (numbers[index] == 3</font><font face="Courier New">)      <br>    {       <br>        </font><font face="Courier New">break;      <br>    </font><font face="Courier New">}      <br>}</font></p>  <p>How to avoid here the break? As one of my bosses taught me, remember the tools at your disposal; A <font face="Courier New">for</font> loop <a href="https://docs.microsoft.com/en-us/cpp/cpp/for-statement-cpp?redirectedfrom=MSDN&view=msvc-170">contains three parts</a>: initialization expression, condition expression and loop/increment expression. Nothing forbids us to add additional checks to the condition expression, as in the following improved code:</p>  <p><font face="Courier New">int[] numbers = { 1, 2, 3, 4, 5 }</font><font face="Courier New">;        <br>bool found </font><font face="Courier New">= false;        <br>for (int index = 0; index &lt; numbers.Length &amp;&amp; !found; </font><font face="Courier New">index++)      <br>{       <br></font><font face="Courier New">    if (numbers[index] == 3</font><font face="Courier New">)      <br>    {       <br>        found </font><font face="Courier New">= true;      <br>    </font><font face="Courier New">}      <br>}</font></p>  <p>We are short-circuiting the loop, but in a soft and more elegant way (and not commonly seen in the code!).</p>