DEV Community

Discussion on: If/else or just if?

Collapse
 
madhadron profile image
Fred Ross

I use both in two different situations. I use the first form at the top of a function when I'm doing assertions about parameters. Think of it as poor man's type checking or contracts in languages that don't have them, e.g.,

def f(a, b):
    if not instanceof(a, int):
        raise ValueError('a must be an int')
    if a < 0:
        raise ValueError('a must be nonnegative')
    ...

I use the second form in the primary body of code unless I am forced to do otherwise. The lazy reason is that I write in both imperative and functional languages, and in functional languages all ifs must have an else statement, so by always having an else, I have one less thing to keep track of between languages.

The more philosophical reason is that using the else block makes it very clear what the branch is in the execution path. The precondition and postcondition for both branches should be the same and the effects required to bridge that gap are all confined to those blocks. I have come to value this kind of locality more and more over the years.

Collapse
 
orenovadia profile image
orenovadia

If you find yourself doing this often, check this out: pypi.org/project/icontract/