Home > Software design >  Should an if-statement end with else in a function that asserts the values
Should an if-statement end with else in a function that asserts the values

Time:10-19

Suppose I have a function with a variable drinks whose values might be extended later on:

def what_to_drink(drinks):
    assert drinks in ['coffee','tea'], "Invalid 'drink' value. Please choose between 'coffee' or 'tea'."

    if drinks == 'coffee':
        print("I don't drink coffee, I drink tea my dear")
    elif: drinks == 'tea':
        print("I am an English man in New York")

Since the values for drinks might be extended, it seems to make sense to use elif instead of else. However, should the if-statement end with an else-statement? This seems redundant since the assert operator already serves as a gatekeeper for unwanted values. However, without the else-statement, the logic seems incomplete.

CodePudding user response:

Edit: As pointed out, by @user2390182 and @TedKleinBergman, the usage of assert in the first place is arguably a bigger thing to consider than whether an else is useful when the logic doesn't allow it to get there. However, I assume here that you have decided to use assert yourself, and will be using it in a way that respects the assert consistently.

Facts:
As drinks always has to be an element of your list, as long as you always have an elif allocated for each item in the list, you will never reach an else and therefore it is unnecessary.

Opinion:
It terms of correct practice what to do in this situation, it's really down to personal choice. The online consensus is often "less code is better" but if it makes your code clearer, or if you're likely to be changing the list of drinks often, it may make more sense to add it as a catch all, to stop anything breaking during your development. As with a lot of decisions like this, you have to take it on a case by case basis, and decide which you think is better in this situation.

  • Related