开发者

for each ... break

开发者 https://www.devze.com 2022-12-14 06:35 出处:网络
I feel dirty every time I \"break\" out of a for-each construct (PHP/Javascript) So something like this:

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.tes开发者_如何学Ct == 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?


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


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.


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.


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 you said ""why not?" It's quick and more importantly easy to understand and follow."

Why feel dirty, I see nothing wrong with this.


I think is is easier to read and hence easier to maintain.


It is meant to be like it. Break is designed to jump out of a loop. If you have found what you need in a loop why keep the loop going?


Breaks and continues are not gotos. They are there for a reason. As soon as you're done with a loop structure, get out of the loop.

Now, what I would avoid is very, very deep nesting (a.k.a. the arrowhead design anti-pattern).

if (someCondition)
{
    for (thing in collection)
    {
        if (someOtherCondition)
        {
            break;
        }
    }
}

If you are going to do a break, then make sure that you've structure your code so that it's only ever one level deep. Use function calls to keep the iteration as shallow as possible.

if (someCondition)
{
    loopThroughCollection(collection);
}

function loopThroughCollection(collection)
{
    for (thing in collection)
    {
        if (someOtherCondition)
        {
            doSomethingToObject(thing);
            break;
        }
    }
}

function doSomethingToObject(thing)
{
    // etc.
}


I really don't see anythign wrong with breaking out of a for loop. Unless you have some sort of hash table, dictionary where you have some sort of key to obtain a value there really is no other way.


I'd use a break statement.


In general there is nothing wrong with the break statement. However your code can become a problem if blocks like these appear in different places of your code base. In this case the break statements are code small for duplicated code.

You can easily extract the search into a reusable function:

function findFirst(objectList, test)
{
  for (var key in objectList) {
    var value = objectList[key];
    if (test(value)) return value;
  }
  return null;
}

var first = findFirst(objectList, function(object) {
  return object.test == true;
}
if (first) {
  //do some process on object
}

If you always process the found element in some way you can simplify your code further:

function processFirstMatch(objectList, test, processor) {
  var first = findFirst(objectList, test);
  if (first) processor(first);
}

processFirst(
  objectList,
  function(object) {
    return object.test == true;
  },
  function(object) {
    //do some process on object
  }
}

So you can use the power of the functional features in JavaScript to make your original code much more expressive. As a side effect this will push the break statement out of your regular code base into a helper function.


Perhaps I'm misunderstanding your use-case, but why break at all? I'm assuming you're expecting the test to be true for at most one element in the list?

If there's no performance issue and you want to clean up the code you could always skip the test and the break.

for (object in objectList)
{
  //do some process on object
}

That way if you do need to do the process on more than one element your code won't break (pun intended).


Use a

Object object;
int index = 0;

do
{
    object = objectList[index];
    index++;
}
while (object.test == false)

if breaking from a for loop makes you feel uneasy.


My preference is to simply use a break. It's quick and typically doesn't complicate things.

If you use a for, while, or do while loop, you can use a variable to determine whether or not to continue:

for ($i = 0, $c = true; ($i < 10) && $c; $i++) {
    // do stuff

    if ($condition) {
        $c= false;
    }
}

The only way to break from a foreach loop is to break or return.

0

精彩评论

暂无评论...
验证码 换一张
取 消