This is a question I've been facing for a while in my college class that I've been thinking about, and I need to get other people's point of views. I searched and couldn't find another question very similar to this one in terms of coding practices.
(Examples are written in Java)
When I write my code, I will generally write methods like this:
public void myMethod(int one, int two) {
if (one >= two) return;
// do things
if (two != one) return;
// do other things
}
Instead of writing methods like this:
public void myMethod(int one, int two) {
if (one < two) {
// do things
if (two != one) {
// do other things
}
}
}
Similarly, I will write my loops like this:
for (int i = 0; i < x.length; i++) {
if (x[i].getValue() > 4) continue;
// do things
if (!xConditionTwo) continue;
// do other things
}
Instead of like this:
for (int i = 0; i < x.length; i++) {
if (x[i].getValue() <= 4) {
// do things
if (xConditionTwo) {
// do other things
}
}
}
As seen here, I look at things sequentially (from top line to bottom line), and it makes sense to me to exit out of the method/loop if that something is not what we're looking for, and we don't require an else statement.
However, when I spoke to my college instructors, they all agreed that if somebody were to write code like this, they would not be hired because said person cannot figure out an algorithm that wouldn't require the use of a continue/return.
My question to everyone is: When is it acceptable to use continue/return to break like this, if at all? Why is this considered bad practice, and how can I avoid using if statements without an else to avoid extra indentation?