0

I have an eternal discussion in my work about why "error first" is "worng".

In order to ensure what I try to tell with error first is the following code pattern:

if condition:
    raise Error()

code

Instead of if-else approach

if condition:
    code
else:
    raise Error()

I think that the first one (error first) is better because you only check your error conditions, you avoid using else statement, by logical error will be raised and never you execute the code.

But on the other hand, probably race conditions or any strange reason, if you encapsulate the error inside an else you are always are setting the logic, and probably is defensive programming approach in order to avoid errors.

The question is there is any reason beyond its de facto standard (in javascript), or there are any other design reasons.

Edit

Another argument is that if only have one error is not enough to do "error first", but anyway I think that if you select an error template for checking the flow of your code you should following in each place including one error code.

Thanks

Tlaloc-ES
  • 387

2 Answers2

11

I prefer the former, because if there are multiple errors then they are handled one after another without further indentation of the non-error code:

if error-condition1:
    raise Error("1")
if error-condition1:
    raise Error("2")

code

Compare with:

if not error-condition1:
    if not error-condition2:
        code
    else:
        raise Error("2")
else:
    raise Error("1")

Here not only does the regular code get indented twice, but the condition1 and Error("1") get separated further the more "code", and the more error conditions there are.  I also don't like the negation as I'd rather test directly for the error condition than the absence of the error condition.

There is another option, which is to swap the then- and else-parts.

if error-condition1:
    raise Error("1")
else if error-condition2:
    raise Error("2")
else:
    code

This is quite readable, though personally I still prefer the else-less version.

Erik Eidt
  • 34,819
5

I’ve seen code doing a few operations that could all potentially fail, with a 20 times nested if. Inserting another error condition after test #11 was practically impossible.

At some point a code structure that handles one condition after the other in a linear fashion is just better.

gnasher729
  • 49,096