I can’t remember ever disagreeing more with Jeff on any issue before.
@Graham:
Comparisons aren’t free, you loose some milliseconds on them. And hiding logical sequencing using and/or tricks when calling your functions and lazy evaluation is bad taste in most languages.
Early returns are a definitive yes if your code is in a critical procedure to be called hundreds or thousands of time per second by other parts of your whole program.
It’s definitely safer and faster (and easier to read) to do this:
my proc{
do_stuff();
if(error){
return error_code;
}
do_more_stuff();
if(final_condition){
return calculated_value;
even_more_stuff();
if(error){
return another_error_code;
}
return another_value;
}
than using boolean flag variables and doing comparisons all the way down:
my proc{
do_stuff();
if(error){
error_detected = true;
return_value = error_code;
}
if(!error_detected){
do_more_stuff();
if(final_condition){
final_condition_reached = true;
return_value = calculated_value;
}
}
if(!(error_detected or final_condition_reached){
even_more_stuff();
if(error){
return another_error_code;
}
return another_value;
}
}
Early return is equivalent to a GOTO, and for good reasons!!!
The Linux kernel code still has some goto’s here and there, mainly on critical error catching stuff. And it’s logical: if an error has been detected, you’d better go fast as fast as possible to the code that deals with the problem.
I just hate single character variable names, they obscure too much the code.
And I have learned to avoid ternary operators as plague over the years. Doing simple stuff like:
int abs(int x) {
return x lt; 0 ? -x : x;
}
Is OK. But time after time in different companies I’ve worked for, I find developers who abuse them. I once found code written by some clever developer who thought using 4 ternary operators (2 of them nested within the other and yet with another ternary expression within) was preferable to the long version using plain old if…else structures.
Guess what? His code had bugs. And it was easier to understand/debug when I rewrote it into several if…else lines.
So I for one am happy some modern languages (like Python) have simply proscribed them. These kind of features (like inheritance and polimorphism) tend to be abused way to often.