4 ms·
I agree. There are cases were break and continue are much more succinct and easier to understand, just as there are with goto (error handling in C for example,
by hkolek 15y ago
I agree. There are cases were break and continue are much more succinct and easier to understand, just as there are with goto (error handling in C for example, see linux kernel). To get rid of them just because someone considers it harmful is stupid. I'd guess the reason Scala got rid of them is not because they're harmful but because they're not very useful in a functional language where you usually don't deal with imperative loops.
- qw 15y agoI could probably live without "break", but "continue" is very useful. for(Person p: persons) { if(p.getAge() < 18) continue; // lines of code here } The alternative is to have a if-else instead, and that hurts readability even if you don't usually have much code inside a for-loop. You could probably also solve it by writing a filter function that generates a new list with those you want to process, but I find having lots of "magic" functions scattered around the code to be just as annoying. And it will also hurt performance / memory usage for large datasets
- jmreardon 15y agoIn scala you would use a for-comprehension to get the same effect: for (p <- persons; if p.getAge >= 18) { println(p); }
- eeperson 15y agoHow is this any more readable than: for(Person p: persons) { if(p.getAge() >= 18) // lines of code here } If anything, I would argue that this version is clearer since it makes the context of execution more explicit.
- z92 15y agoUnless you have multiple of these conditional checks when the indention level gets unholy. Continue in loop is like early return from a function. Some say we should not use it. But other find it really painful to work without 'continue'. I remember moving whole body of a loop into a function call only to get "continue" support in Lua though early return.
- eeperson 15y agoWhy would this cause indention level to get bad? Couldn't you simply chain these conditions in a single if statement?
- z92 15y agoNot if you need to pre calculate before some conditional checks, do something if some conditions are meet and you want to save state. Basically it all comes down to organizing code. Removing 'continue' removes one's ability to organize code in a good way, as some see it.
- mark242 15y agoActually, the functional alternative in scala is this: persons.filter(_.age >= 18).foreach(p => { (code here) }); That is way, way more readable, imho.