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

preview_player
Показать описание
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:

▶ Follow me on Instagram:
Рекомендации по теме
Комментарии
Автор

You know your code's bad when it looks like HTML but isn't HTML

Natural_Power
Автор

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

andrespereira
Автор

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.

coolcodingcat
Автор

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

waffle
Автор

I can't thank you enough, keep these amazing videos coming please!

Notmoyo
Автор

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)

sagshah
Автор

Good knowledge. Enough content to fill one minute video only, though.

Thorrief
Автор

Can you do a quick follow-up video to check time efficiency?

federicoperalta
Автор

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.

AWriterWandering
Автор

What is the theme setup used in this video?

iamshiva
Автор

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.

tylerbakeman
Автор

Speaking of being concise, this video could've been 1/4 as long.

Jkfgjfgjfkjg
Автор

So multiple returns is better than nested if?

BarDots
Автор

I find that basic solutions are often the best solutions🙌

etgaming
Автор

Indently urging us not to indent... irony.

pragyanOne
Автор

I always use this way nowadays to get rid of unnecessary intendation. I call it the "return early" pattern.

erik....
Автор

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.

Zhiroc
Автор

What is really cool, you made ~2 minutes topic somehow into 8minutes. That's real skillz.

kutilkol
Автор

This would be textbook case for style in python?
try: connect()
except connection_error, payment_error, no_internet_error, user_not_online_exception: solve_the_problem

TheBayru
Автор

Also useful if you need to add another condition later on in an update. 😊

amacleod