3 ms·
I quite often find myself writing code like (in Java): Fruit edibleFruit = null; for (Fruit f: basket) { if (f instanceof Banana) { if (!f.isDisc
by twic 12y ago
I quite often find myself writing code like (in Java):
Fruit edibleFruit = null;
for (Fruit f: basket) {
if (f instanceof Banana) {
if (!f.isDiscoloured()) {
edibleFruit = f;
break;
}
} else {
if (!f.isMouldy()) {
edibleFruit = f;
break;
}
}
}
And getting rid of the nasty assign/break pairs by extracting a method:
Fruit edibleFruit = edible(basket);
Fruit edible(Collection<Fruit>: basket) {
for (Fruit f: basket) {
if (f instanceof Banana) {
if (!f.isDiscoloured()) return f;
} else {
if (!f.isMouldy()) return f;
}
}
return null;
}
But your idea would let me clean up without having to extract a method (here, in a hypothetical Java-with-value-bearing-break):
Fruit edibleFruit = for (Fruit f: basket) {
if (f instanceof Banana) {
if (!f.isDiscoloured()) break f;
} else {
if (!f.isMouldy()) break f;
}
}
You need to have a story about what happens if there isn't a break - if the loop exits normally. You could implicitly return null, but that's a terrible idea. Better would be to require else clauses on value-returning loops (a bit like the else clauses that Python allows on try blocks):
Fruit edibleFruit = for (Fruit f: basket) {
if (f instanceof Banana) {
if (!f.isDiscoloured()) break f;
} else {
if (!f.isMouldy()) break f;
}
} else null;
Yes, i'm still returning null here, but at least i have to do it explicitly, which makes me feel bad about it and think about finding a better alternative!