IMO, using break
in a while loop isn't that bad. But I can guess why the speaker said that.
So if I have a while loop like this:
while (condition1) {
if (condition2) {
break;
}
// do other stuff
}
You can definitely make the code shorter by doing this:
while(condition1 && !condition2) {
// do other stuff
}
The speaker might think that break
s in a while loop are not neccessary because you can just write all the conditions where you are supposed to write them i.e. in the parantheses.
However, this is not the case. If I have this while loop:
while (condition1) {
// do other stuff
if (condition2) {
break;
}
}
How do you change that so it doesn't use break
?
while (condition1) {
// do other stuff
if (condition2) {
condition1 = false;
}
}
That doesn't seem really nice to me.
Let's put this into a piece of kind of meaningful code. Which do you think is more readable:
while(noWallInFront) {
walk();
if (sawFriend) {
sayHi();
break;
}
}
or
while(noWallInFront) {
walk();
if (sawFriend) {
sayHi();
noWallInFront = false;
}
}
Obviously the first one, right? The second one sounds like you're treating your firend like a wall.