Nesting “If Else” Can Seriously Damage Your Code Quality, Do THIS Instead In Python

129,285
0
Published 2023-01-10
It’s very easy to fall into this trap with Python. You have a lot of conditions that depend on other conditions, and they all need to be handled appropriately. But that can easily become unmanageable, so it’s time we take a look at a good alternative; the guard clause pattern.

▶ Become job-ready with Python:
www.indently.io/

▶ Follow me on Instagram:
www.instagram.com/indentlyreels

All Comments (21)
  • @Natural_Power
    You know your code's bad when it looks like HTML but isn't HTML
  • Applied this to my pytho script and this changes the looks of my code 180 degrees. Thanks a lot for this little tuto. Here is your like and comment buddy
  • @coolcodingcat
    I used to do a lot of nesting of if statement, but that was because I had read and had been taught it was bad to have more than one return statement per function.
  • @waffle8364
    This is also called inversion of your if statements. handle the sad paths first by inverting the statements, this forces the sad paths to the top
  • @sagshah10
    Hi thank you for another good tutorial and please take this as positive critism. I agree with you about the issue of reducing else statements, however I dont agree with your suggested solution, you have unnecessary return statements which could be avoided using `elif` statements instead. Also I generally would have prefered one function call to print, here is my recommended solution for this: def go_online(): message = 'You are online' if not connection: message = 'No connection...' elif not paid: message = 'User has not paid...' elif not internet: message = 'No Internet...' print(message)
  • @Notmoyo
    I can't thank you enough, keep these amazing videos coming please!
  • @AWriterWandering
    As an alternative to returning, you can also use ‘elif’. if not connection: …. elif not paid: …. This will have similar functionality, except instead of returning, it jumps down to the bottom of the if-elif-else block. Personally, I do just used the return , but there are programmers who don’t like the idea of early returns.
  • @Thorrief
    Good knowledge. Enough content to fill one minute video only, though.
  • @jakecomay9138
    Can't you just do: if not internet: print("No internet") elif not paid: print("user has not paid") else: print("You are online") it seems a lot more readable and it less lines of code
  • @tylerbakeman
    I don’t usually run into this issue. Usually it’s something like: void f(){ Element e=value; if(e != null){ if(collection.contains(e)){ // single block } } } Your demo says to invert it into this: void f(){ Element e=value; if(e!=null) return; if(collection.contains(e)){ // single block } } Weird. The compiler should skip the second if statement im both cases (assuming it fails the first one). Your approach does highlight a common topic— if the bools are dependent/ independent on the previous bool, then that should affect the nesting. Some benefits to this inversion: possibly saving memory (less localized variables), which helps performance a little. Modularization— it’s more organized (in your case). Personally, I think this technique might be compiler specific. I think we shouldn’t be worrying about our branching statements ~this much — again, they run in O(1), and aren’t the bottleneck of performance — so a lot of projects really wouldn’t benefit from making this change. I think what your teaching is really niche, and doesn’t really apply to many situations, where it benefits them — a lot of nested-if statements are inter-functional, and we can’t always adopt methods for control flow in them. I think youre tackling an “issue”, that isn’t an issue: why are we trying to make coding more complicated? (In your case, it is more readable— In my case, it is less readable). While I appreciate the very small amount of saved memory, I also think it’s important to recognize that the compiler might perform worse — transversals of if statements could affect its ability to optimize the cycle times of them.
  • @TheBayru
    This would be textbook case for "easier to ask forgiveness than permission" style in python? try: connect() except connection_error, payment_error, no_internet_error, user_not_online_exception: solve_the_problem
  • @kevon217
    Great tip. Much cleaner and readable.
  • @kutilkol
    What is really cool, you made ~2 minutes topic somehow into 8minutes. That's real skillz.
  • @erik....
    I always use this way nowadays to get rid of unnecessary intendation. I call it the "return early" pattern.
  • @Zhiroc
    This is fine if your conditions are prerequisites, and you can "fail fast". And I agree that reducing nesting is an admirable goal. But a lot of situations are more nuanced than this where conditions are not fail/success, and where you sometimes have to "unwind" yourself to clean up things when a failure does occur. Also, it's not good to fail "too quickly" as it's annoying when something tells me I have something wrong, I correct it, and then it tells me the next thing that's wrong when it could have told me about it in the first place.
  • @pragyanOne
    Indently urging us not to indent... irony.
  • @etgaming6063
    I find that basic solutions are often the best solutions🙌
  • @Jkfgjfgjfkjg
    Speaking of being concise, this video could've been 1/4 as long.
  • @iamshiva003
    What is the theme setup used in this video?