Home > database >  Is it better to use 'elif' or consecutive 'if' statements alongside return state
Is it better to use 'elif' or consecutive 'if' statements alongside return state

Time:09-25

This question is specifically regarding coding convention. I know that using if or elif in this case will produce the same results. Just wondering which is the "proper" way to construct this function:

With consecutive if:

def can_take(self, selectedCourse):
    if selectedCourse.hasPassed():
        return False
    if selectedCourse.getPrereqs() != 'none':
        for prereq in selectedCourse.getPrereqs():
            if not self.courses[prereq].hasPassed():
                return False

    return True

With elif:

def can_take(self, selectedCourse):
    if selectedCourse.hasPassed():
        return False
    elif selectedCourse.getPrereqs() != 'none':
        for prereq in selectedCourse.getPrereqs():
            if not self.courses[prereq].hasPassed():
                return False

    return True

CodePudding user response:

If I had to choose between the two, I would probably use two if statements, but that's just a matter of personal preference.

If I had a third choice, I wouldn't have any return statements with Boolean literals. I would write a single return statement that uses and and or.

return (not selected.hasPassed()
        and (selected.getPrereqs() == 'none'
        or all(x.hasPassed() for x in selected.getPrereqs()))

This is close to how you would describe this in English: you can take the class if you have not passed it, and if the class either has no prerequisites or if you have passed all the prerequisites.

As John Kugelman points out, if getPrereqs returned an empty list instead of 'none', you could further reduce this to

return (not selected.hasPassed()
        or all(x.hasPassed() for x in selected.getPrereqs())

CodePudding user response:

I love the early return pattern:

Get invalid cases out of the way first, either simply exiting or raising exceptions as appropriate, put a blank line in there, then add the "real" body of the method. I find it easier to read.

Returning early keeps the nesting level down, which is great way to reduce cognitive load. I would take it one step further and flip the second if statement around so it too returns early:

def can_take(self, selectedCourse):
    if selectedCourse.hasPassed():
        return False

    if selectedCourse.getPrereqs() == 'none':
        return True

    for prereq in selectedCourse.getPrereqs():
        if not self.courses[prereq].hasPassed():
            return False

    return True

That said, some other improvements I would make:

  • Avoid stringly typed variables. Switch that 'none' to None.

  • But then, when a method that returns a list, don't return None when there's nothing to return. Return an empty list. Then the caller can blindly iterate over the list without checking if it's None or empty.

def can_take(self, selectedCourse):
    if selectedCourse.hasPassed():
        return False

    for prereq in selectedCourse.getPrereqs():
        if not self.courses[prereq].hasPassed():
            return False

    return True

If you're comfortable with generator expressions you could even convert the loop into an all(...) call, removing the need for the final return True.

def can_take(self, selectedCourse):
    if selectedCourse.hasPassed():
        return False

    return all(self.courses[prereq].hasPassed()
        for prereq in selectedCourse.getPrereqs())

I like this because it's a more direct encoding of the question: "Has the student passed all of the prereqs?"

CodePudding user response:

In your case if one of the condition is True then you have to return False. Then you need an elif. If you have a scenario where both needs to be checked then only you need if seperately. Above you are returning from function so you need an elif.

CodePudding user response:

I think I prefer the first version. Why? When you have an if...elif...elif... thing with returns in each branch, there are two "competing" control structures: the if statement and the returns. Obviously, the returns will "win", so we might as well remove the elif stuff. Either that, or have just one return statement, which returns a value computed by a preceding if...elif...elif...else structure.

CodePudding user response:

We use elif but please understand it depends on your problem statement.

Note: Please do not create a big ladder out of it as then it becomes difficult to maintain and debug the code.

CodePudding user response:

Always prefer elif with the if conditions, because when one condition become satisfy it left all of the rest conditions which is so good for the efficiency of our code..

  • Related