Nesting "If Statements" Is Bad. Do This Instead.
Vložit
- čas přidán 19. 09. 2022
- Never nest your if statement if you have to many of them. With the Guard Clauses technique, you will be able to write cleaner and more readable code. In this video you will learn how to replace the if statement from you code by the guard clauses technique. This technique is actually simple to understand, all you have to do is to reverse the if else condition and put all the code under. You can reverse every if else condition and at the end you will have you function. Keep in mind that some people don't like to have empty return statement, so you can change this part of the code if you need. This was how to replace your big nesting if else statements in your code with the Guard clauses technique.
COURSES
Flutter courses (Beginner & Advanced): www.fluttermapp.com/
MISSION
Our mission at Flutter Mapp (Flutter Mobile App) is to help purpose driven Flutter developers go full-time doing what they love and making an impact through coding. We achieve this with useful Flutter tips and straight to the point Flutter videos.
RECOMMENDED VIDEOS
Playlist of more than 200 Flutter tips: • 35 Flutter Tips That W...
Learn Flutter in 1 hour: • Flutter Tutorial For B...
Zero to Hero Flutter Course (Beginners): • Video
Hero to Pro Flutter Course (Advanced): • Video
EDITOR
Amaan Ansari: / amaan_0605
SOCIAL MEDIA:
Instagram : fluttermapp
Twitter : FlutterMapp
Website: www.fluttermapp.com
Discord Invite: / discord
CONTACT
For business inquiries email me here: info@fluttermapp.com
Website: fluttermapp.com
#fluttermapp
#shorts
#Flutter
Ahhh yes. The "early return" technique.
Not bad tho
Nothing wrong with early return. It's an issue in C if you have to free a resource before exiting, then every return also has to do that clean up which is error prone. In C++ if you use RAII, then it's a non issue and simplifies the function.
@@johnbrooks5903 goto is a babe tho
@@sleaf6 uses goto☠️☠️☠️
@@sleaf6 spaghetti code incoming 😬
I also take this approach, but I really hate hearing "this is wrong". It's just another way to do it that you and I think is less readable, it's not wrong.
Exactly, finally somebody with a wider look.
In my opinion early returns that don't return a value are often a bad practice as they interupt program flow.
When reading or debugging code I am generally not expecting any return operations from a void function.
If-else statements do a so much better job in that case.
@@jongeduard I think it's just the lack of a keyword in this case. return is used, but it'd make more sense if it said "break" just to signify it should stop execution from then on.
Talking about whether or not it's "wrong" is just subjective, I think it's wrong because it won't make it past most code reviews, so why write it? Our job is more than just making functional code it's making readable, maintainable code others can pick up.
It's not intrinsically wrong (well nothing is...) but depending on the industry in which you code you can have (a) stricter or laxer set(s) of standards. Which will force you to have, for example a maximal nesting depth, or no multiple returns or no generic/empty list initializer etc etc. Main thing is to write clean logic in maintainable code, written to the standard's boundaries in the particular field/industry you are coding for.
@@jongeduard there is an example in "Clean Code" book same as the video, nothing wrong with early return in the small function like that, and function should be small so early return is good
Would saying "This is suboptimal" be better, or...?
"If you need more than 3 levels of indentation, you're screwed anyway, and should fix your program." - Linux kernel coding style guideline
Flutter left the chat.
C# which method bodies have 3 levels of indentation: :)
@@arsikkbar"then you should fix your program"
linus speaks for me 🗣️🗣️🗣️
fix it by doing this but checking for three conditions isnt bad lmao
The "AND" operator has left the chat.
AND operator wouldn't fix the problem in this example
@@xLAMCHOPPED I can write a lot better code without this many if. This video totally goes the opposite direction of what it is supposed to teach.
How tf would it help?
Using the && operator while keeping the original functionality would result in 1 if statement, 2 else if statements, and one else statement. This would make the code even more dogshit disgusting than before, though more readable.
“and” wouldn’t allow you to print a specific error message for each missing piece of data. Not without getting uglier than this, anyway.
Just imagine if you forget the return statement in the admin check. Everyone becomes admin
Woah
Imagine if you have faulty unit tests in the whole codebase
This is totally a rookie argument. If you have more than 6 month software dev experience you should be ashamed.
Just imagine if you make everyone admin. Everyone becomes admin
No, they just get to see the admin panel. If they tried to do anything on it that actually required admin privileges, even just code on it that fetches sensitive data to populate the views, you would get access denied errors.
If you are relying on frontend code to do security for you, you have much bigger problems. They could literally just open the dev console and modify the value of "admin" directly.
showing the admin panel as a default is good because coders never make mistakes nor do they ever forget to check edge cases
Exactly what I thought. His code could become insecure in a hurry as it gets complex.
Well that escalated quickly.
Doesn't make a difference in this case. If all three requirements are fulfilled you'll get to see the admin panel either way. He didn't change any logic, only how the code is written.
@@Kanal-yh5xi No, in the nested ifs, you need 3 boolean to be true. In the guard clauses, you just have to forget one return and it will show the admin panel even if not all 3 boolean are true
@@renlidacha Your functions should be small enough and stick to SOLID principles as much as possible. Having all your checks at the top of the function should make it pretty easy to see if you miss a return statement.
"Weve been hacked what happened!"
"I forgot a return sir"😂
It's a frontend code though
@@ShivamJha00it could be backend in SSR but the design would have to be aweful
As a security consultant, I find this horrifying. Yes, this works to block non-admins from seeing the admin panel. However, you really should be doing the "isAdmin" check at the top. In more complex codes, doing the check after other code blocks unnecessarily increases the attack surface... there are more chances for something to go wrong and introducing exploitable code. The lesson here is: in any function where the ultimate show-stopper of the function is a crucial security decision, do the check as warly as possible. Not doing so is like having a security guard who watches thieves loading their truck and only gets up to do anything after several minutes of deep meditation about the situation.
I'm very certain the admin thing in this short is just an example to teach how to nest the ifs. I agree that this example is not a clever one as you stated, but this is not to teach security.
@윤형석 the focus isn't to teach security. You are correct. However, if security isn't considered from the start, then it will have to be retrofitted into the product later, which is a much more monumental task that is a lot more expensive and much less effective with unforseen problems that arise down the road. And often, they are never resolved until SHTF. I've been doing pentesting and security consulting for 10+ years, and I've seen this over and over again. This video is a great example of nesting, but it is contributing to bad habits that developers learn from the beginning that they carry with them throughout their careers. The only thing I wanted more from this video was a different placement of the admin check function and a 5-second explanation as to why it should be at the top from a security point of view.
@@zsi Very well understood. Using better examples is always better even when they're not the focus.
I like the analogy😂
😂
To anyone new learning how to program. *THIS IS NOT WRONG*. It’s great to learn how to do something many ways and build your personal coding style off of others and try to balance your coding style with the readability that may suit a team, but it’s not wrong. If you’re new to programming this is called preference. The cool and neat thing about programming is that you can arrive at the same solution many different ways. So don’t be afraid to do this when you feel it’s appropriate
Yeah a lot of times in larger functions these early outs end up causing their own readability problems where you have to keep scrolling up to see what assumptions you’re working with. Of course people will say just make your functions shorter but in real life shit happens and sometimes you end up with less ideal scenarios. Moral of the story is you gotta just learn to make trade offs because there’s never going to be one single consequence free approach.
the compiler won't complain but it's still a garbage technique and if you use it to handle admin privileges you should get fired
Yeah this is very wrong. It is a very error prone method with catastrophic consequences in case of error, that's called wrong pratice.
@David Freer Thank you so much. I code for a living but I'm still not super experienced. Your comment puts these kind of videos in a better context.
This could have been phrased differently. Here is a common coding practice that can cause some readability issues and here is an alternate approach that can help mitigate it. Both techniques dont always apply and having more options and tools in your tool belt is always goos
Reminds me of my internship days. There was a small function with lots of nested IFs. So I've gone ahead and broke the rule of thumb "If it works, don't touch it". I refactored all of those nested IFs with early returns. Guess what? There was a pieces of code at the end of the function do the calculations. Thanks to my early returns, it f*** the whole thing up.
Why not just separate the calculation into a separate function?
@@houmy9041 That wouldn't have helped. Instead of the function erroneously not doing the calculation code, it would have erroneously not called the new function to do the calculation.
@@rosiefay7283 Presumably you *could* have solved it with more and more refactoring, but there's a point at which it's not worth the time, risk of introducing bugs, or potential increase in complexity.
Now I want to see what the function was
So the calculation was outside, not conditional to the if logic. Just meant you refactored the code wrong and changed the overall functionality.
With the example given the functionality was not changed. Meaning same outcome doing it differently. And the lesson you learned when refactoring - understand what it is doing before making the change.
As some one who writes a fair bit of code everyday this technique is pretty solid. Nesting if statements can get hairy
For anyone saying the Logical AND (&&) would help, no it wouldn’t really help. Why is that?
As he demonstrated, he has these neat little debug prints, which tell the user what they require in order to access the admin panel. Just doing "&&" and printing "Cannot access admin panel" if one of the conditions fails would be WAY to unspecific.
So remember, debugging is VERY important. I've been doing it this way many years, and it saved me a lot of nerves, trying to read the code.
Its funny, when I was at university, this exact thing was described as "hard to read" and "bad", with multiple and/or nested if/else statements being preferred.
The grass is always greener.
There’s usually a reason someone is being paid less to teach code instead of being paid more to write it…
@@artificiallyunintelligent4537 Typically the people teaching it do it after writing it for years/decades,so...
@@wlt3585 Typically where?
Most teachers in my university come from university, and got the job without doing some actual work in the market
@@dionisietarlev7081 I'm not bold enough to speak for all of the United States, but it is very common for the professor to go teach after years of experience in the actual workforce. A notable exception though is when graduate students are required to teach a course for a semester or a year for their study, which is fairly common.
Again, I can't say this is how it is everywhere here, but it happens enough to where I would consider it the norm
@@artificiallyunintelligent4537 xD Profs are easily in the
It comes naturally I think. I usually start with messy ifs when bootstrapping the logic then I convert it to something more readable
takes time tho i would do this kinda stuff immediately. and if you do need a nested if statement you most likely need a separate function to either do more stuff in it or return something
@@imluctor5997 yeah more often than not I refactor those statements into different functions to keep the code concise and reduce code repeating
@@imluctor5997 I find that doing it messy and knowing it works every time is better. You could use the messy portion for unit testing 😝
@@imluctor5997 yeah it's easier to reason about when writing functions to do it this way from the start. "I need a function which takes in a,b,c and returns X. If I don't have a throw, if I don't have b, throw, if I don't have c, throw. Ok now I can do what I need to do to get X."
Absolutely! Nobody writes good code on the first go around. The first pass is to make it work. The next passes are to clean it up.
As someone who is been coding for good while now. To any beginner out there, there is no such thing as a "wrong way", but rather this one way to do it. It all comes down to preference and how we write our code, for me personally I had no trouble reading the nested if statements.
I am just learning and I had no trouble. Granted these aren't very complicated to read, but the IDE's make it easy to keep blocks of code straight.
These things are always case by case. The only wrong approach is thinking one size fits all.
As someone who is still fairly early in the programming learning curve, I appreciate you and other experts in the comments calling out the one size fits all black and white approach these videos create.
I tend to be a perfectionist, so constantly worrying about if I'm doing best practice means I don't learn or finish anything. There's so much context missing from shorts like these. When you're starting out, good practice is important, but what's more important is learning the concepts and thinking of things through the lens of a programmer.
I've also seen a lot of people absolutely trashing on the mindset of "this is not wrong, just different" or "this is not wrong, just not always best practice" and it's very disheartening to see that kind of animosity towards common beginner mistakes. It seems like a great way to chase people away from programming, if you ask me.
@@theConcernedWyvern this is pretty much always better, I agree you should think for yourself and apply things differently for different cases but this is just the best way to do it. Nested anything is almost always harder to read
as someone who's been writing code for 25 years, there absolutely is a wrong way. Just because something works does not mean it's a correct way. And frankly, if anyone finds nested IFs confusing or hard to read they're really going to struggle when they come across code that's actually complex.
And in all honesty, the admin check should be first.
Back a year later after seeing this and it has changed how a i code and the readability of my code thank you so much
Ruby actually has an "unless" keyword for this reason and it makes guard clauses even better
do people use it?
At least for Perl, the common recommendation is to avoid "unless" for complex conditionals and statements requiring elsif/else clauses.
@@guerra_dos_bichos i've only seen it used for one line guard clauses like "return false unless condition"
i could see that working, because you don't have to invert the condition for something valid
@@D0Samp I guess I never got that memo. The whole point of unless() is to simplify the conditional, syntacticly. It's not going to fix complex logic, but it also won't make it any worse. Whichever keyword avoids double-negatives and results in the most obvious control flow is the one you should use, IMO.
To avoid the multiple return statement fight, just bring your subsequent statements into else if clauses. Now it's a single block where any failure ships to the end. Also allows for continuing code afterward (if minimal changes to existing codebase are required) or other pass through type flows
Else if works not in this example
@@Juus if(not WiFi){
debugPrint('Must be connected');
} else if (not login) {
debugPrint('Must login in yo...');
} else if (not admin) {
debugPrint('Must be an admin...');
} else {
seeAdminPanel();
}
// do other handling before return statement
Seems to work just fine on a phone, in a comment
@@tychozzyx9439 Ahh I see, was my bad. I thought too complicated
They're essentially the same thing. I prefer the other version only for readability purposes
@@tychozzyx9439nerd
This is easily the best programming tip you can give a beginner, instantly clears up code and makes everything easier to understand by a factor of 700x
As someone who uses “if (thing) return” instead of nesting it is 100% worth learning if you don’t know how. It can seem backwards but seems natural after a bit of practice. It’s more condense, easier to read, and faster to write.
Also, since there seems to be arguing about using “and” and “or” statements you definitely can still use them.
After having to interact with others’ code with nested if statements I really appreciated this method even more.
Tip for developers: In most cases, do not follow this.
While this is actually good advice, I recommend that you (mostly) stick with nested if-conditions.
This is because nesting conditions makes the complexity of your methods more visible. If you see your code getting messy with nested if-else statements then that is your sign to split your method, apply better separation of concerns, etc.
It also helps to make it more obvious if/when you're not properly covering certain branches of code when unit and integration testing.
Exactly, why would one throw 4 different cases in 1 file of code, separating the logic is the way to go.
I mean I had a case where for ex. Login page has different cases but 1 final outcome, which in JS i use Switch statement: if user is missing email field, or missing password field, or wrong, or pw/email combination is wrong; but ALL of that has 1 outcome: login failed, and my Switch statement is used to alert the user with the correct message.
If i were to have admin-only page, that would be another file(s) of code.
@@Winter_Wyvern1 Yeah the two situations where I use guard clauses are: 1) Parameter guards that throw exceptions because theoretically the parameters should never be invalid, and 2) situations like yours where the outcome is roughly the "same" but maybe slightly different output and little to no difference in logic.
Totally a rookie argument. ALWAYS code for readability. There is no such thing as "too many ifs".
If the business logic required it there can be a dozen guard clauses!
ONLY if you have other design goals to pursue this becomes and issue:
1) The same guard clauses in multiple places?
2) Guard clauses must be configurable, monitored etc.
3) Aspect oriented programming. THe guard clauses should be modularized.
@@michaelrenper796 have you heard of "personal preference"? Not everyone has the same opinion in regard to readability so your fist sentence is only valid to a certain point.
@@1zui Personal Preference? I presume you have never worked on a team. Readability is about other people being able to read and maintain your code. Coding guidelines are NEVER about YOUR preferences.
Doing early returns is fine, but balance is key. Nested conditionals are not wrong, in fact it can help to visualize the structure of the code, especially in more complex codepaths. Over use of return statements can lead to confusing and harder to debug code.
Just like with all coding tips, you need to know when to appropriately using them. Functions, nested loops, return statements, etc. all have a purpose, but use them where they should be used appropriately.
For instance, functions are great for cleaning up code, but if you are using them every few lines, it becomes completely unreadable and makes it hard to find bugs.
@@troybaxter The only right way to code is to write everything in one line. Everything else is meek.
@@KucheKlizma I agree. You are not a true computer programmer if you aren't condensing your 100,000 line program into one single line.
Bro this is so helpful. I really Appreciate it!
Swift developers: ok
Never used swift. Can you explain pls? :D Edit: Ok i read in the comments...Guard :)
@@dosenbiiir Maybe Swift has something similar to Rust's expression matcher (a variant of switch/case)? I guess
@@Rudxain yeah i think what he means is called Guard in Swift. Some other comments mentioned it here
@@dosenbiiir oh yes! I read about it just now. A cool feature is that it doesn't allow fall-through, which makes code pretty safe
@@Rudxain Yeah I also checked it out now. Nice Feature!😃
I'm just sitting here trying to figure out if you're a québécois based on your accent
😂😂 Yep!
The accent tells it all
@@lieutenantpepper2734 no kidding
Instant Spotted. That is my accent xD
I went in the comment just for that reason 😂
I like this and have done it for decades.
Now I have a name for it.
Thank you.
You can also remove the brackets and do "return debugprint" on the same line as the condition
You can't just say, "It's wrong!" There are always different cases. You just need to decide in each particular case how to balance the amount of nesting and "early returns" (or whatever the folks call this).
nooo... lol get real cmon now.
I can and will say it's wrong if my eyes have to nest 5 levels deep in junior dev if else shit storm to read the logic 😂
pft... JavaScript devs
Unless you're OK with slow software.
seeAdminPanel as default statement is just wonderful.
😂 i was thinking it too
Why is it wrong? Not trying to offend, I'm genuinely curious.
@@Thomas7994 If all other cases fail then automatically it shows admin panel. Typically you would not want regular users to see "Admin" stuff on your website
enclose it with (wifi && login && admin) just for precaution ?
@@OligoST I don't see any way for the admin panel to get displayed if user is not logged in as admin...
If all other cases fail, the code hits 'return'.
when I graduated college, at my first job the programming standard was every function should only have one return. Now it's good to have several returns (which I agree)
Return early - that technique has been around for decades.
My coworkers insist that it's an even worse sin to have multiple return statements.
Professors in my classes in the late 90s early aughts taught that, as well. They seemed to think "return" was akin to "goto" for some reason. Like returning to the calling function wasn't something a conditional should do. Never really understood.
It holds value and contributes to clean code when done right but ultimately it's a matter of preference.
Your coworker is not Donald Knuth, he's nobody, so he should shut up
It's absolutely not, some people think that but it's literally fine
then your coworkers are wrong. spaghetti code uses a lot of nested ifs and is totally unreadable because of it.
The “wrong” way of doing it isn’t really wrong, it just has a different set of advantages and disadvantages that make it sometimes preferable and sometimes not.
Advantages like what?
@Dave Bieleveld ... like what?
@Dave Bieleveld Maybe. It's tough to discuss without specific examples. But basically, pretty much every programming language has sufficient facilities to allow you to build logic that doesn't have to resort to overly complex conditions. If you use all of the available tools and mind the idioms.
If you're nesting conditions like this, you should 100% of the time double check to make sure your code, and more importantly the code it's building on top of, is truly legible and organized.
It's kind of a warning sign that the app may not be handling data as responsibly and cleanly as it should. Just something to think about.
if it works like it should it isnt wrong
@@hiperion_1416 This depends on whether you're working with other engineers or not. If you're on a team or simply open source, it's definitely wrong to write code that's sloppy or illegible. Machines just read machine code; the language you're using is so that humans can read it too.
Someone send this to Yandere dev
why doesnt that man just use switches. he's in Unity is he not???
@@doriondouglas6176 A bit late in the responses, but from the code leak a LONG while ago. No, no he does not. Or to be accurate he doesn't use them for long chains of conditionals.
@@doriondouglas6176Well the funniest part is, he actually did but he's not calling the separate method for the switch statement. He technically just "rewrote" the infinite nested if-statement into a switch case just to brag his "coding skills", while technically he's not following the coding standards.
Though, switch case would've been a little better, but abstraction and using for-each is the best approach to enhance performance and increase code readability.
Something like using individual constant variables for specific values (if they have multiple occurences) is a massive contribution in code clarity and readability.
@@doriondouglas6176the if and switch case is a meme, unity converts if conditionals into switch case anyway, practically there's no difference in performance between the two , his code is dogshit for other reasons
Excellent recommendation! I’ve been doing this for years and it is much more readable!
You can combine the gaurds with ORs into a single conditional. You can further pull out the negations into a single negation and change the ORs to ANDs. You can further rearrange your terms such that the most expected false term is first. Short-circuiting will work through a negation in JavaScript.
I may have misunderstood but surely combining them with an or, or negating and combine with ands would only work if the else's all had the same logic ... They're all logging different things, so
```
if (!admin || !wifi || !login) { blah ; return }
showAdminConsole()
```
Won't work
In the early 90’s my teacher would chop my head off if I broke the flow of a flow chart by having multiple exit paths in the flow.
Exactly my thoughts
and they were so wrong
Flow charts are a great way to torture students with, but not particularly useful otherwise.
Just depends on the language and situation, maybe?
I've heard plenty of pushback regarding guard clauses. I'm personally highly in favor of them because of how much they have simplified my code and logic overall. I'm open to being persuaded otherwise though.
@@baka_baca it was the teachers of the 90’s that were wrong. Programming paradigms are developing all the time, though back then it was Pascal and assembly language we were taught.
The guard clauses definitely makes for more readable code. I use them all the time myself.
This is a great video to learn the concept and while there's better ways to implement these specific checks, that's not what this video is about.
Code scuffed from nesting? Scuff it instead with short-circuiting! (Protip: restructure code instead of doing this)
Finally, a reasonable take.
one guard clause at the very top of a method is fine, it's a problem once you start having multiple early returns all over the place
I was about to say the same thing. It seems that admin and all its appropriate messages should be bundled into its own separate function (the purpose of OOP in the first place).
or you could do
if(!wifi) {Error 1}
else if(!login) {Error 2}
else if(!admin){Error 3}
else {loginPanel();}
if you use else you can still clean up the code without return. this way you could run additional code underneath the if statement. either way the original if structure isn't the wrong way. The returns are optimal but also break out of the function.
this is the proper way
That's it. People forgot about the throw statement.
Switch case can be cool to do here, I think
This works but if-else has been proven to not be optimal from a performance perspective
@@vacannot yeah so what's the solution for running code inside the function under the ifs or needing to throw error codes? I don't think we're concerned with the login page taking an extra 0.01ms to run if else
No need for all these if statment when the expression is the same in all cases.
Just use single if statement and chain the conditions with &&.
This will also make sure the function has only one return statement which is also good practice 👍
The main reason he hasn't is because of the specific error messages for each condition
Also, nothing wrong with multiple early returns
@@maxsteffey6521 if (wifi && login && admin) {
seeAdminPanel();
} else if (!wifi) {
debugPrint("Must be connected to the internet");
} else if (!login) {
debugPrint("Must login in your account");
} else {
debugPrint("Must be an admin");
}
You can have multiple if without having multiple return clause if you don't do anything between the if anyway. that's what an if else is for. having multiple if with return inside in a function that return nothing doesn't add anything to this short example, it just make the function unnecessary long without adding to the readability.
you can reverse my if else to get the errors first if you prefer, doesn't really matter in that case. The point is that you don't need to early quit when it's not necessary.
hes just explaing for beginners calm down guys
@@maxsteffey6521 He could create a separate function that returns an object, with both a response for the error and whether the validation was successful - { isValid: false, reason: "User is not Admin" } - then you could compare something like validAdminLogin(user).isValid in the "if" statement and .reason, in the response.
The thing I like about this tip is that it is applicable is almost any coding language
For readability I usually check if whatever language I'm using has syntax for case when. Always made most sense to me coming from predominantly sql.
This is so helpful that Swift has introduced a dedicated "guard" statement for it! They enforce that control flow exits the scope in their body, so whenever you see the word "guard", you can assume that it condition holds for the rest of the scope.
I personally do not like early returns but if the nesting gets that deep I will consider this.
never heard of DBC?
But now every if statement must be in the right order. If u have many if statements, u better dont f*** the order up. The best way to write this in my opinion is: If (wifi and login and admin) showPanel else message('error: not wifi or not logged on or not admin')
The idea is that do not check anything, if the other conditions has failed, you organize the if’s most likely to fail to least likely, resulting in fewer checks. Its not just about the code style.
i am just so proud of myself that programming education video just pop up in my feeds.
the usual are :
- video games
- vtuber
- music
- etc etc etc
That's good. It can be seen often in linux kernel codes.
We commonly call it protective programing. The language like Swift even makes it as language feature.
De Morgan wants to know your location
kkkkkkkkkk
He knows by what you don't reveal
Was thinking this too.
i love how the "stairs" look like so ill just leave it like that
Thanks for sharing!
Very good explanation buddy very informative thank you for making life easy
I just read it like it's Reddit and it's alright
Or push the error messages onto an error array/stack/list, and then exit with a single summary of all errors seen. (Same idea, but much cleaner and more useful.)
I think that's what the debug message function does, but just throw an error if you want a proper stack trace
This idea is cool when validating forms or requests.
Awesome approach. Never thought about this. Thank you very much!
if(wifi && loggedin && admin) to show the adminpanel, and then if(!wifi) print_statement would be a good alternative as well. You don't have early returns, you don't have nested ifs, and your admin panel check, print statements, ext. are all separate and individual- very good for readability.
In this example I would have added an && clause if using C#...
If (wifi && login && admin)
{
SeeAdminPanel();
}
Else
{
Report an error string...
Return;
}
yes, but we do not know which of the flags (wifi, login or admin) has failed and thus we can't print the specific one
@@kylekeenan3485 okay, but how are you gonna decide which exception string to throw? that's right, you need if-else statements or guard statements. just because you hide it behind a function does not make it go away.
also, ignoring that, exceptions are something you should AVOID unless you really need them. please do not do this. this is not good practice.
@@kylekeenan3485 Oh my god, never ever do this
@@gianni50725 what you could do is actually create a Boolean array and have each index equal a certain Boolean check.
Alarm[1] = failPassword
Alarm[2] = failWifi
Alarm[3] = failAdmin
Then you can take that Alarm array and map it to a Warning list and print out the corresponding warnings.
It may be more complicated in this particular instance, but in more complex situations it would be good to have a function or script that stores all your Alarms, that way you have a centralized location of your alarms, and you know if you are accidentally triggering the wrong alarm.
@dino dina I wouldn’t say yuck. Just centralizes warnings and alerts. It really helps with readability and quickly understanding what went wrong.
For most software I'd agree your code looks more readable and is probably better. But I'd be hesitant in to call something absolutely right or wrong in the software industry. Nested ifs are unreadable but readability not always the highest priority.
Having multiple returns in a function can have its own set of problems. Here are two examples:
1. Preventing side-channel attacks based on runtime. Sometimes hackers can use the runtime of code to get information out of a system e.g. if your server takes significantly longer to respond to a faulty login with an existing user than with an non-existing one, hackers can use that information to check whether a certain account exists on your system. For security relevant code you want to have all your branched code to perform roughly the same operations. So no early returns because they shorten the runtime of that branch.
2. If you use model checkers or are formally proving that a code is correct (e.g. for software for an airplane or anything safety related), multiple return statements make it harder to prove pre- and post conditions. If you have a lot of those in a complex algorithm the problem grows exponentially. So in order to make it easier to prove you might want to ditch readability.
You need high readability to easily debug your code.
Especially the code you didn't write, or worse, you write it but it's 6 month ago.
I think to calm both sides of the debate down, we can use this solution (implemented in Python):
if not wifi:
print("You are not connected to the internet.")
elif not login:
print ("You must be logged in.")
elif not admin:
print("You are not admin.")
else:
displayAdminPanel()
No worries about bad programmers forgetting to put a return, and keeping the readability of what the video suggests.
I still slightly dislike that you have to put a "not" in front of every condition. That is imo more error prone than the return statements. I'd probably go for a chain of "and" statements of the positive conditions to evaluate access to the potentially sensitive content you are trying to protect. Then, after the core business is done, I'd start stepping through the individual "if not X" statements to do error handling.
This isn't always easier to understand, since you're now dealing with stacked negatives, which the human brain isn't so good at dealing with. Lack of understanding can lead to errors when the code is changed to incorporate any additional aspects.
if this is harder for you to understand you probably haven't code a lot
@@SheelByTorn 30 years, and very successfully. My own development company. So I speak from experience. How about you?
@@SheelByTorndont be so stupid. If im not asleep im coding & i have spent 2 years doing support (actually fixing bugs in code) that use the 'early return' technique & the system is nothing but problematic. Most of the senior devs dont even understand their own code because its far too large & you quickly convolute the logic in the code for the person reading it.
This is how a Haskeller would structure the logic using guards. You need to code more.
You can also use a enum with states (if your language supports enums or similar) and check values a switch block.
In the next short, we learn the benefits of GOTO.
oh god
I prefer COMEFROM from the Intercal language. It is the same, but worse.
Even John Carmack says that we still
need a GOTO statement.
bro is saving lives here!
Thank you! I am still learning
I have been using it for years without knowing the name 😂
I call this the "precondition pattern"
There are very rare cases where code is straight up just wrong. Some people don't want to do this method since they may not read it, and others may prefer it that way. From what I see, technically your "return" statements could break the program since it ends the condition too early. Realistically, the return should be at the very end to prevent early termination of the conditional.
Most IDEs or interfaces like VScode allow you to click on arrows that close a conditional as well, making it easier to read if you need to bounce back and forth.
There is also always an easier way as well, functions are useful for conditions like this. For example:
If you are logging in, it then calls a function to either log in as an admin or a user. Then call another function to check if the information is correct AND if the person logging in is an admin.
Ah...I usually refer to this as the "error first" style.
This approach is particularly useful in situations where multiple conditions need to be evaluated.
BTW, if there is no need to separate multiple conditions, it is also helpful to combine them in a single if statement using "||".
Wont that OR result in all statements having to combined before checking the result, not saying its bad thing, considering you get fewer branch, but… is it always better?
It’s not wrong. It’s just one way to do it. I usually think of how I would further develop the method.
Hold up this looks like the stuff I saw in my symbolic logic class. I may have to give coding a try. I loved that symbolic logic class and was great at it.
well coding has a lot of logic since the CPU ultimately understands 1s and 0s (true and false) and everything is built on top of logical circuits.
@@soniablanche5672 The CPU doesn't understand binary, it only understands its instruction set. To execute its instruction set, the CPU also needs to understand twos complement integers, IEE745 floating point, and also the frame buffer understands ascii characters encoding.
That's about it. CPUs are really, really dumb.
You're spot on! This is just DeMorgan's law - instead of executing code if Thing1 AND Thing2 AND Thing3 is true, you break out of the loop when Thing1 OR Thing2 OR Thing3 is false, and execute the code otherwise.
@@RadixTheTroll Cool. That works well for me.
@@asdfxyz_randomname2133 OK, next we're going to talk about micro code and ticks. But I agree, as a coder you should know the inner workings down to the bottom. I recommend ben eaters channel, because he is a good teacher and very consistent.
It's De Morgan theorem, example : "if you study then you pass" can be said as "either you don't study or you don't fail."
Early return, early exit, negative checking - makes for clean code. 👌
damn, how come I only saw this after I submitted 1000 unhealthy lines of code to my professor...
It's a good thing you didn't see this, this is "asking for trouble" code...
ah yes the "this is always good, this is always bad" technique
viewers (humans) love this. They don't have to think or consider things anymore. "some youtube short told me to always use this, so I'm always right"
And then, because your code wasn't clear, you have someone who is not an admin have the admin panel opened, because you forgot a simbol, somewhere.
Just code in a way it's easy to understand.
One of the best ways that i learnt in C++ before when i was beg,
It's not bad, and you almost always need a contrived example like your "if (admin) if (admin) if (admin)" to make the case.
Many languages forbid you from even having explicit exit points, because it's not declarative. And in situations that require manual resource management, early exits are a hazard.
Me with 'elif'
*laughing maniacally*
"elif" leads to inefficient code, because it encourages you to perform branch-specific initialisations (that should go between "el" and "if") before the outer "if", wasting CPU cycles for branches that are not executed.
@@kleinebre I never understood people interested in micro-optimizations. The performance impact of those extra cycles will be almost impossible to notice.
that's great idea dude
Binary operators have left the chat
the thing is I think he wants to log a different error message depending on the condition
next video from this channel:
Binary operators are bad for readability.
@@isma92 And you can still log different error messages. Since this example only has one "true" path anyway, just run all the comparisons in the first if statement. In an else, resolve for the debug message in a case, switch, table or whatever and print it there. I like this because it lets you consolidate the debug messages together as well. I'm not saying he's wrong, it's just another way to do it (and he's wrong for saying another coding style is wrong).
Admin access as default and credential validation being its own function aside, regardless of your thoughts on early return statements, why not just use else if? It's more readable imo as the code itself describes what you're doing better. Though I will say it ties the reminder of the code into an else block.
If you're willing to put more effort in, I would prefer to create an InvalidCredentialsException and throw it so I can handle how to display/log the message better. I think this is how the guard pattern is generally implemented as exceptions let you send information back to the caller while not messing with the original return type and they make it much clearer for the caller on what they should proceed with especially if the return type is not void (would you just return null in object cases? and 0/false for primitive data types? What if those are valid returns? How can I tell the caller this failed?)
While I don't think it's terrible, I definitely would not go as far as to say just use this.
i always do this because its cleaner, readable and i love it 😁
I would fire your ass for this bs.
I love you
@@Brukrex I love your mom
but it is not
@@orkhepaj Agree. If someone on the team I'm leading submitted a PR with either of these, I would reject and request for changes right away.
It's not hard to eliminate the empty return statements and the multiple return statements, so you only have one return statement and it actually provides meaning.
Bellissimo video!
This is really useful. Thank you
no, check ideal case first. he dumb tard person... 1 branch
if(admin && widi && login) {
seeAdminPanel();
}
else {
console.log( /* message containing state for all three */ );
}
Me being real programmer: goto statement
Segmentation Fault be like: 🗿
Well, in essence a return is also a goto with extra wrapping. A return does the job if it’s a simple function, but the moment you need to start handling complex error conditions or have stuff you need to close you need gotos
So just negate the whole function love it
These shorts are super useful
For some things you could use await too
I didn’t realize there was a name for that
Me too 💪🗿👍
Gladly there's a name for pretty much every pattern :D
I generally dislike the look over overtly nested things. Currently working on a Compilers in OCaml, and it's great, but I really need to refactor it, because there's too much nesting of match case
Excellent teaching... More such teaching please ❤
I’m gonna have to try this out. Merci mon frère!
It is important to note that this is NO LONGER IDENTICAL BEHAVIOR.
If you use the initial program with nested if statements, the debug prints happen after the higher level administrative privileges if-statement is executed, whereas the guard clause improved version executed them before. Small difference here, MUCH bigger in a real program.
software developers are hardcore gatekeepers, change my mind.
You're clearly new here. Maybe brush up a little more before commenting, skid.
@@cc_par welcome to the joke how may I take your order
@@MonkeyBoyKHS pathetic.
Program with me and I'll change your mind to "most software developers..."
@@nallid7357 well clearly not a mathematician lmao; you are not "most" as a single programmer.
It is just good way to exception and exit conditions handling
Thanks bro Ithelped me a lot to make i simpler
One entry, one exit works better. They figured that out 40 years ago.
And we moved on from that close to 40 years ago. Returning early is a general best practice for a long, long time.
@@BasketOfPuppies Not really. It makes it harder to miss set up and tear down portions of functions, and it's part of standards like IEC 61508, ISO 26262, and MISRA C that are currently in place. These standards are required for any code used in safety-critical systems like automobiles, for example. I admit there are exceptions to this rule, like in trivial one-liner functions with some checks where it's very easy to see what's going on at a glance, like in this example, and I'm okay with that. And I admit that we write more one-liners these days, but we didn't leave the general principle of one entry, one exit 40 years ago for non-trivial code.
I claim that the main reason people are ok with this is the prevalence and blatant overuse of exceptions in popular programming languages. It's totally fine to put 100 exit points in every function, because we got that cool RAII feature to help us, or a python context manager thing, or a try-finally block. It's driving me nuts sometimes
The CZcams algorithm has sensed that I am learning c# and is ready to tell me all the reasons I suck lmao
The default example was way more readable and easier to understand. :)
I use to work at a company where your code had to be approved by the lead dev. The guy would refuse your PR if you had any guard clauses because he hated them.