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

132,002
0
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

コメント (21)
  • 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
  • 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
  • @Notmoyo
    I can't thank you enough, keep these amazing videos coming please!
  • @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)
  • 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.
  • @iamshiva003
    What is the theme setup used in this video?
  • @Thorrief
    Good knowledge. Enough content to fill one minute video only, though.
  • @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.
  • @kevon217
    Great tip. Much cleaner and readable.
  • @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
  • this really getting compact with those conditions 🤟🏾 me too not a fan of nested condition ,What if dependency b/w condition any idea ,
  • @BarDots315
    So multiple returns is better than nested if?
  • @etgaming6063
    I find that basic solutions are often the best solutions🙌
  • @PKOVBPK
    Hi Man I have one question and I can´t find answer. I read temperature which is float number. I have some zone from -10 to 10. And when I break this zone from outside I want to make action. if temperature > -10: do someting. elif temperature < 10: Do someting. But what is my problem? When I run microcontroler and actual temperature is -5.5. So I need to know how to specify the barier that when I´m already inside zone from -10 to 10 to do nothing. And when I break zone from outside to iside do what I want. I hope it´s clear. Can you help me how to solve it? Thank you so much :)
  • @LegionLeague
    What about creating helper functions for each "if"? E.g. check_connection(), check_payment(), etc that return a boolean. And then the go_online() function would look like: def go_online(): if all(check_connection(), check_payment(), check_internet()): print("You are online!") Would that work?
  • @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.