jxie0755
jxie0755

Reputation: 1742

Should I always complete all conditions even if some are empty?

Should I always complete all possible conditions even if some of them I don't have any action to move, especially for the non-pure functions

Quick example:

def add_somenumber(lst):
    if len(lst) == 0:
        lst.append(1)
    elif len(lst) <= 5:
        lst.append(5)
    else:
        pass

Or it could be:

def add_somenumber(lst):
    if len(lst) <= 10:
        lst.append(0)
    elif 10 < len(lst) < 20:
        pass
    else:
        lst.append(1)

And the above can be written as:

def add_somenumber(lst):
    if len(lst) <= 10:
        lst.append(0)
    elif len(lst) >= 20:
        lst.append(1)

The function itself has no meaning, but in this situation, should I skip the else part?

The reason is that if I only have if and elif it might lead to the question if I considered all conditions. But then the else part seems quite useless.

Upvotes: 0

Views: 61

Answers (2)

Jaron
Jaron

Reputation: 117

In your situation, the else condition is doing nothing at all, so it doesn't make sense to have it.

But you also ask about wondering if you've considered all situations. When writing programs that need to be more robust, it is always good practice to have a catch for unconsidered events, either through logging or raising an exception. In this case, you would implement it with an else to check when the other two conditions were not evaluated to True.

Example:

def add_somenumber(lst):
    if len(lst) == 0:
        lst.append(1)
    elif len(lst) <= 5:
        lst.append(5)
    else:
        raise Exception('lst had an unexpected length')

or

def add_somenumber(lst):
    if len(lst) == 0:
        lst.append(1)
    elif len(lst) <= 5:
        lst.append(5)
    else:
        print('lst had an unexpected length') # or you can log this

Upvotes: 1

Ben Van Camp
Ben Van Camp

Reputation: 136

There is no right answer here, it's merely a question of style.

However, when I encounter a situation like this (a block of code with no meaning), I usually just whack it. The fact that the block is there insinuates to your code's maintainers (or your future self) that it has some purpose and is unnecessarily confusing.

Upvotes: 2

Related Questions