Avoiding the break statement

Some coding guidelines and best practices advice against the use of continue and break statements.

With continue the solution is easy, placing an if (or if it existed to call continue, negate it to execute the code).

But with break, 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 break sometimes in my code if avoiding it is going to be worse for readability.

The most common case of using the break statement is looping through an indexed array of elements searching for something:

int[] numbers = { 1, 2, 3, 4, 5 };
for
(int index = 0; index < numbers.Length;
index++)
{
if (numbers[index] == 3)
{
break;
}
}

How to avoid here the break? As one of my bosses taught me, remember the tools at your disposal; A for loop contains three parts: 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:

int[] numbers = { 1, 2, 3, 4, 5 };
bool
found
= false;
for
(int index = 0; index < numbers.Length && !found;
index++)
{
if (numbers[index] == 3)
{
found
= true;
}
}

We are short-circuiting the loop, but in a soft and more elegant way (and not commonly seen in the code!).

Posted by Kartones on 2009-11-25

Comments?

Share via: Twitter Linkedin Google+ Facebook