Should one use break in going?

Asked

Viewed 3,187 times

20

I have a question about the loops of repetitions. I had a class in which my teacher said that one should never use the for if you don’t execute it from start to finish.

Only I’ve seen many, many codes using this repeating structure containing a break in the middle to stop.

Is that wrong? What’s the problem of wanting to iterate over a list and if you find what you want, stop ?

I mentioned this to him and the same states that in these cases, I should not use the for because it would not be an elegant solution/strategy.

Does this proceed ? In cases where I have to stop the loop in the middle, I should opt to while or while and just use the for for cases I will process all the elements from x to N?

  • 1

    I wonder when he said that, he was thinking about for that we use by setting a number so much that we want to iterate. Because in that case, if we know the number, there would be no need to use the break. We must remember that the for can be used for many other operations in addition to increments of 1..9.

  • He was giving examples with all operators and stating that it should be and only used for cases we know how far to go. In other cases, we should opt for while or while.. That’s why I was confused about this, because I use it a lot to iterate list and look for something I want and stop the process

  • 3

    @Wallacemaxters even in this case may have several reasons to break the for. It is common to have code that must go from 0 to 9 unless he discovers something along the way. It will only be ridiculous if he makes a for this way and have a break like this: if (i == 5) break;

  • @Wallacemaxters I guess you didn’t understand what I wrote, but okay.

4 answers

19


I don’t know if he’s speaking any specific language. I’m going to speak in general terms.

Some people are dogmatic.

This option even makes sense. Semantically the for would indicate that you want to go from one point to another and there should be no interruptions. Some people will say that if there is to be an interruption then use a while. It seems to me a preciousness that gives no advantage, certainly no technique. At most it passes the idea that it can stop at any time and does not need to go to the end as specified in for. This is if everyone involved with the code follows this rule.

There is no mistake in this, but if you work on a team (your class is your team right now) and it says you should follow this rule, follow it. Not without questioning, of course, how you’re doing. That’s good. But if you don’t have a problem following the established rule and "everyone" agrees with it, don’t be different.

Elegance depends a little on taste. Some things are universal, others do not. For my taste I would not follow this blindly. Could be that some case I chose a construction or other for other reasons but hardly for this presented.

Even the performance could make me choose one or the other, in some specific situations.

Looking at Onosendai’s reply something came to my mind: you make a for that goes from start to finish, then a beautiful day needs to change the implementation and finds a situation that needs to have an interruption in a given situation. You would be "obliged" to change the for for while? Why? You can do it, but it doesn’t seem necessary, something that will add something to the clarity of the code, on the contrary. I think in some cases use a while when it sweeps a sequence, even if it can be stopped, it may even make it less clear what that is in fact. I think less clear, but not much less, I would also not strongly oppose this change, the code would still be clear enough.

Reasons to choose one of the two

A good reason to opt for while is when the control variable will be used outside of the loop.

Perhaps the main advantage of for about the while is precisely encapsulate the control variable in the loop scope. If you don’t need this, the for loses strength.

If you do not initialize the variable outside of the loop the condition remains, that the while has, and the step to be executed in each repeat.

This step is already criticized by some people since it is written at the beginning of the loop but is only executed at the end of it. Remembering that the condition is executed at the beginning.

Of course it’s okay to declare and/or initialize the variable outside of the loop using a for. There are only fewer advantages.

And it’s good to remember that there are languages that have no internal block scope in the code of a function, so it makes no difference to them.

But the big reason to choose one of the two constructions is precisely when there will be interruption of the normal flow but still within the loop. How do you want the step to be executed if there is a jump to the end of the loop? Do you want it to run every time or should the step be omitted if there is a jump? Example:

for (i = 0; i < 10; i++) {
    ...
    if (condiçao) {
        continue;
    }
    ...
}

The i will be increased even if it enters the if and the flow is diverted. Already:

i = 0;
while(i < 10) {
    ...
    if (condiçao) {
        continue;
    }
    ...
    i++;
}

I put in the Github for future reference.

It will skip the increment of i when you enter the if. This is a semantic change that produces a very different result. And it’s not easy to simulate this using the wrong construction. Some people may try and cause bigger problems, even a running condition.

Did the professor talk about this? If not, I expect you to speak in the next class, because this is something fundamental to know about the choice of one or the other construction. This has real practical implications in the code.

Avoid interruptions

The mgibsonbr response speaks well about this. The ideal is not to have break or even a continue. This is a goto and everyone knows that goto is of the devil (please read my reply on link to understand the sarcasm).

Well, it’s a better way to goto And although we try to avoid this kind of construction, we should not do this at any cost. If it’s to write a convoluted code, it’s preferable to break or continue, or even a goto in much rarer cases and make the code clearer.

The same goes for a return which is a break more aggressive. And wear a return, even inside a loop, it’s not something bad.

  • 1

    +1 by the interesting point - code normalization. If a development team uses one or the other as a standard, always follow it; much better than 20 excellent implementation styles is a good and unique style.

  • I understand and agree to follow the standards already adopted by the team. The real problem that brought me was to think that all the code I wrote using the is and interrupting it could have been written in a very bad way. Anyway, thank you very much for the reply, gave me a great clarity on that. :)

11

In a strict sense, does not proceed. In several real situations you have objects that can change state during the execution of a loop, and the treatment can induce an assessment that the loop is no longer necessary or valid - the loop interruption being the most desired attitude.

Another factor would be performance. In C#, for example, language control mechanisms can cause a noose for is more performatic than a while.

  • 2

    Exactly. In many situations we know the beginning and end of our bond and so we can opt for the is, but no one guarantees that no object state changes and that we need to take another measure.

10

Break a loop in the middle (any loop, not only the for) brings a downside which is to make it harder for the programmer to understand what state the program is in. Regardless of the construction employed, this problem exists. Sometimes it’s inevitable, but when you can structure your code to make it clearer to human readers, it’s worth doing.

As to the for, I would break its use in two cases basically:

  1. The control variable of for is unique to it, not being used anywhere else.

    Example:

    for ( int i = 0 ; i < lista.length ; i++ ) {
        ...
        if ( condição )
            break;
    }
    

    What will be the value of i at the end of the loop? Well, that’s irrelevant! No one will use i out of the loop, incidentally depending on the language i nor will there be more at this time. So the use of the break does not interfere in anything the understanding of the code.

  2. The control variable of for is used more than once, maybe even by more than one loop.

    Example:

    // Remove um elemento de uma lista
    int indice;
    for ( indice = 0; indice < alvo ; indice++ )
        destino[indice] = origem[indice];
    for ( indice++ ; indice < origem.length ; indice++ )
        destino[indice-1] = origem[indice];
    

    In that case, if the first for had a break, what would be the value of indice after its termination? It could be anyone, and you would have to program very carefully not to assume an incorrect value. Observe the stopping condition of the for does not help you, because the value of indice would not necessarily equal alvo at the end of the first loop, not equal to origem.length at the end of the second.

    Use a while in that case it would help? Little - you still wouldn’t know what the exact state of indice after each loop. The utility or not of it depends on the expectations programmer when reading the code. If you already expect a while may contain breaks, but does not expect the same to happen with a for, then you will pay more attention to that detail if a while. Otherwise it makes no difference...

The key ready is to adjust the expectations of those who are reading your code with what the code actually does. If everyone agrees to a convention, then the best thing to do is to follow it, or at least document every time you deviate from that convention (for good reason, preferably). After all, it makes no difference driving left or right, since all drive on the same side... ;)

  • Good examples, especially the second case!! Thank you very much for your reply, it was very helpful!!

  • A reasonable example of when you should prefer the while is precisely when the control variable should be used outside the loop, regardless of whether or not there is a break.

5

Perhaps this depends on language. But this would be more a matter of good practice recommended by your teacher, than having "a right" and "a wrong". I say this because there are people who use statements like "you can’t do this".

There are cases of languages, such as Python, for example, where we can use a for for other types of iterations (such as lists, objects, generators), which is not common in other languages.

An expression that would return an infinite Generator, for example, might require the use of a break to end this infinite loop.

In other cases, in languages such as PHP, where we can use a foreach to iterate with a array or a Iterator, there is no need to use the for.

  • Yeah, I also thought it was a matter of good practice he recommended. But it was a very interesting point, it made me think a lot about the codes that I did until today, and as I have little time in the area, I never thought that this could be a "problem".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.