Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for each ... break

I feel dirty every time I "break" out of a for-each construct (PHP/Javascript)

So something like this:

// Javascript example

for (object in objectList)
{
   if (object.test == true)
   {
      //do some process on object
      break;
   }

}

For large objectLists I would go through the hassle building a more elegant solution. But for small lists there is no noticeable performance issue and hence "why not?" It's quick and more importantly easy to understand and follow.

But it just "feels wrong". Kind of like a goto statement.

How do you handle this kind of situation?

like image 812
ChronoFish Avatar asked Dec 11 '09 17:12

ChronoFish


4 Answers

I use a break. It's a perfectly cromulent solution.

like image 161
Paul Tomblin Avatar answered Oct 03 '22 16:10

Paul Tomblin


It's quick and more importantly easy to understand and follow.

Don't feel bad about break. Goto is frowned upon because it's quick and more importantly not easy to understand and follow.

like image 28
Jere Avatar answered Oct 03 '22 16:10

Jere


See, the break doesn't bug me at all. Programming is built on goto, and for-break - like all control structures - is merely a special-purpose form of goto meant to improve the readability of your code. Don't ever feel bad about writing readable code!

Now, I do feel dirty about direct comparisons to true, especially when using the type-converting equality operator... Oh yeah. What you've written - if (object.test == true) - is equivalent to writing if (object.test), but requires more thought. If you really want that comparison to only succeed if object.test is both a boolean value and true, then you'd use the strict equality operator (===)... Otherwise, skip it.

like image 29
Test Employee 2 Avatar answered Oct 03 '22 15:10

Test Employee 2


For small lists, there's no issue with doing this. As you mention, you may want to think about a more 'elegant' solution for large lists (especially lists with unknown sizes).

Sometimes it feels wrong, but it's all right. You'll learn to love break in time.

like image 45
Daniel May Avatar answered Oct 03 '22 14:10

Daniel May