by qw · 15y ago · 0 comments
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 for (p <- persons; if p.getAge >= 18) {
println(p);
}persons.filter(_.age >= 18).foreach(p => { (code here) });
That is way, way more readable, imho.
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.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.
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.