Nesting "If Statements" Is Bad. Do This Instead.

Поделиться
HTML-код
  • Опубликовано: 19 сен 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

Комментарии • 3,3 тыс.

  • @Chevifier
    @Chevifier 6 месяцев назад +115

    "Weve been hacked what happened!"
    "I forgot a return sir"😂

    • @ShivamJha00
      @ShivamJha00 3 месяца назад +2

      It's a frontend code though

    • @ParasGupta-ce9bj
      @ParasGupta-ce9bj 23 дня назад +1

      @@ShivamJha00it could be backend in SSR but the design would have to be aweful

    • @IFeatherStone
      @IFeatherStone 6 дней назад +1

      That should all be checked in testing

    • @machariawarui6686
      @machariawarui6686 День назад +2

      Tell me you don't test your code without telling me you don't test your code

    • @WolfRaven-jm1cm
      @WolfRaven-jm1cm День назад

      ​@@machariawarui6686 "I did test it! I was able to login to the admin panel with my admin login!"

  • @diegovera6858
    @diegovera6858 Год назад +13229

    Ahhh yes. The "early return" technique.

    • @TheRealZitroX
      @TheRealZitroX Год назад +291

      Not bad tho

    • @johnbrooks5903
      @johnbrooks5903 Год назад +1098

      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.

    • @sleaf6
      @sleaf6 Год назад +283

      @@johnbrooks5903 goto is a babe tho

    • @daanhoek1818
      @daanhoek1818 Год назад +632

      @@sleaf6 uses goto☠️☠️☠️

    • @notRealCapedBaldy
      @notRealCapedBaldy Год назад +303

      @@sleaf6 spaghetti code incoming 😬

  • @user-vu8fm5vb4n
    @user-vu8fm5vb4n Год назад +2035

    "If you need more than 3 levels of indentation, you're screwed anyway, and should fix your program." - Linux kernel coding style guideline

    • @warred
      @warred Год назад +99

      Flutter left the chat.

    • @arsikkbar
      @arsikkbar Год назад +68

      C# which method bodies have 3 levels of indentation: :)

    • @rya3190
      @rya3190 6 месяцев назад +25

      ​@@arsikkbar"then you should fix your program"

    • @CrazycatASG
      @CrazycatASG 6 месяцев назад +6

      linus speaks for me 🗣️🗣️🗣️

    • @Lintee_Second
      @Lintee_Second 5 месяцев назад +4

      fix it by doing this but checking for three conditions isnt bad lmao

  • @crewrangergaming9582
    @crewrangergaming9582 Год назад +5571

    The "AND" operator has left the chat.

    • @xLAMCHOPPED
      @xLAMCHOPPED Год назад +759

      AND operator wouldn't fix the problem in this example

    • @crewrangergaming9582
      @crewrangergaming9582 Год назад +354

      ​@@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.

    • @DD-rn4gi
      @DD-rn4gi Год назад +44

      How tf would it help?

    • @mister_hamana
      @mister_hamana Год назад +406

      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.

    • @jackdog06
      @jackdog06 Год назад +613

      “and” wouldn’t allow you to print a specific error message for each missing piece of data. Not without getting uglier than this, anyway.

  • @Underliner0000
    @Underliner0000 Год назад +7706

    Just imagine if you forget the return statement in the admin check. Everyone becomes admin

    • @spoopyscaryskelebones3846
      @spoopyscaryskelebones3846 Год назад +98

      Woah

    • @________________404
      @________________404 Год назад +457

      Imagine if you have faulty unit tests in the whole codebase

    • @michaelrenper796
      @michaelrenper796 Год назад +268

      This is totally a rookie argument. If you have more than 6 month software dev experience you should be ashamed.

    • @epicgameryt4052
      @epicgameryt4052 Год назад +213

      Just imagine if you make everyone admin. Everyone becomes admin

    • @fennecbesixdouze1794
      @fennecbesixdouze1794 Год назад +188

      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.

  • @sb_dunk
    @sb_dunk Год назад +7766

    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.

    • @jongeduard
      @jongeduard Год назад +426

      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.

    • @moon_bandage
      @moon_bandage Год назад +115

      ​@@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.

    • @marian-gabriel9518
      @marian-gabriel9518 Год назад +67

      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.

    • @hoanggiangtran2062
      @hoanggiangtran2062 Год назад +33

      @@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

    • @RaceBandit
      @RaceBandit Год назад +13

      Would saying "This is suboptimal" be better, or...?

  • @zsi
    @zsi Год назад +825

    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.

    • @technocracy90
      @technocracy90 Год назад +78

      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.

    • @zsi
      @zsi Год назад +67

      @윤형석 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.

    • @technocracy90
      @technocracy90 Год назад +11

      @@zsi Very well understood. Using better examples is always better even when they're not the focus.

    • @rishi_rajani
      @rishi_rajani Год назад +6

      I like the analogy😂

    • @primer6714
      @primer6714 Год назад +1

      😂

  • @notagamer8782
    @notagamer8782 9 месяцев назад +12

    As some one who writes a fair bit of code everyday this technique is pretty solid. Nesting if statements can get hairy

    • @manuel8123
      @manuel8123 2 дня назад +1

      I was assigned to do some updates to a program we use internally.
      While reading the code I found a 56 level if else statement to check if all 56 entries on the database were inserted correctly, I was flabbergasted when I found it...

    • @notagamer8782
      @notagamer8782 2 дня назад

      @@manuel8123 that is terrible

  • @mikezheng33
    @mikezheng33 Год назад +1998

    showing the admin panel as a default is good because coders never make mistakes nor do they ever forget to check edge cases

    • @zwz.zdenek
      @zwz.zdenek Год назад +286

      Exactly what I thought. His code could become insecure in a hurry as it gets complex.

    • @Carhill
      @Carhill Год назад +41

      Well that escalated quickly.

    • @Kanal-yh5xi
      @Kanal-yh5xi Год назад +67

      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.

    • @renlidacha
      @renlidacha Год назад +158

      @@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

    • @nebraskacoder
      @nebraskacoder Год назад +58

      @@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.

  • @davidfreer2166
    @davidfreer2166 Год назад +1043

    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

    • @alexandercordova3856
      @alexandercordova3856 Год назад +46

      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.

    • @rnbpl
      @rnbpl Год назад +15

      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

    • @shiva9551
      @shiva9551 Год назад +24

      Yeah this is very wrong. It is a very error prone method with catastrophic consequences in case of error, that's called wrong pratice.

    • @heyyou274
      @heyyou274 Год назад +7

      @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.

    • @avibrenner1580
      @avibrenner1580 Год назад +12

      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

  • @rax7223
    @rax7223 Месяц назад

    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

  • @RandomYouTubevids-bl7sc
    @RandomYouTubevids-bl7sc 6 месяцев назад +1

    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

  • @samsonwu9378
    @samsonwu9378 Год назад +731

    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.

    • @houmy9041
      @houmy9041 Год назад +24

      Why not just separate the calculation into a separate function?

    • @rosiefay7283
      @rosiefay7283 Год назад +88

      @@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.

    • @KGH3000
      @KGH3000 Год назад +72

      @@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.

    • @guyfromdubai
      @guyfromdubai Год назад +10

      Now I want to see what the function was

    • @veritasliberabitvos454
      @veritasliberabitvos454 Год назад +43

      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.

  • @oblivioncth
    @oblivioncth Год назад +912

    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.

    • @artificiallyunintelligent4537
      @artificiallyunintelligent4537 Год назад +102

      There’s usually a reason someone is being paid less to teach code instead of being paid more to write it…

    • @wlt3585
      @wlt3585 Год назад +248

      ​@@artificiallyunintelligent4537 Typically the people teaching it do it after writing it for years/decades,so...

    • @dionisietarlev7081
      @dionisietarlev7081 Год назад +37

      @@wlt3585 Typically where?
      Most teachers in my university come from university, and got the job without doing some actual work in the market

    • @wlt3585
      @wlt3585 Год назад +102

      @@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

    • @MrHaggyy
      @MrHaggyy Год назад +18

      @@artificiallyunintelligent4537 xD Profs are easily in the

  • @cryptic_daemon_
    @cryptic_daemon_ Год назад +60

    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.

    • @FighteroftheNightman
      @FighteroftheNightman Год назад +1

      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.

    • @shmosel_
      @shmosel_ 5 месяцев назад +5

      These things are always case by case. The only wrong approach is thinking one size fits all.

    • @theConcernedWyvern
      @theConcernedWyvern Месяц назад

      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.

    • @rax7223
      @rax7223 Месяц назад

      ​@@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

    • @phaelax
      @phaelax Месяц назад +1

      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.

  • @bluealteran4599
    @bluealteran4599 Год назад +183

    Ruby actually has an "unless" keyword for this reason and it makes guard clauses even better

    • @guerra_dos_bichos
      @guerra_dos_bichos Год назад +7

      do people use it?

    • @D0Samp
      @D0Samp Год назад +6

      At least for Perl, the common recommendation is to avoid "unless" for complex conditionals and statements requiring elsif/else clauses.

    • @bluealteran4599
      @bluealteran4599 Год назад +11

      @@guerra_dos_bichos i've only seen it used for one line guard clauses like "return false unless condition"

    • @xybersurfer
      @xybersurfer Год назад +1

      i could see that working, because you don't have to invert the condition for something valid

    • @nickwallette6201
      @nickwallette6201 Год назад +2

      @@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.

  • @xrayian
    @xrayian Год назад +744

    It comes naturally I think. I usually start with messy ifs when bootstrapping the logic then I convert it to something more readable

    • @imluctor5997
      @imluctor5997 Год назад +21

      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

    • @xrayian
      @xrayian Год назад +12

      @@imluctor5997 yeah more often than not I refactor those statements into different functions to keep the code concise and reduce code repeating

    • @nicholasfinch4087
      @nicholasfinch4087 Год назад +9

      @@imluctor5997 I find that doing it messy and knowing it works every time is better. You could use the messy portion for unit testing 😝

    • @buzz1ebee
      @buzz1ebee Год назад +1

      @@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."

    • @Nonsense116
      @Nonsense116 Год назад +5

      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.

  • @CodeTom
    @CodeTom 11 дней назад

    Bro this is so helpful. I really Appreciate it!

  • @eugenecbell
    @eugenecbell 7 месяцев назад

    I like this and have done it for decades.
    Now I have a name for it.
    Thank you.

  • @tychozzyx9439
    @tychozzyx9439 Год назад +145

    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

    • @Juus
      @Juus Год назад +1

      Else if works not in this example

    • @tychozzyx9439
      @tychozzyx9439 Год назад +69

      ​@@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

    • @Juus
      @Juus Год назад +16

      @@tychozzyx9439 Ahh I see, was my bad. I thought too complicated

    • @quandaviousvonheadsonzingl6453
      @quandaviousvonheadsonzingl6453 Год назад +2

      They're essentially the same thing. I prefer the other version only for readability purposes

    • @Crecross
      @Crecross 8 месяцев назад

      ​@@tychozzyx9439nerd

  • @garrafote18
    @garrafote18 Год назад +111

    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.

    • @troybaxter
      @troybaxter Год назад +2

      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.

    • @KucheKlizma
      @KucheKlizma Год назад +1

      @@troybaxter The only right way to code is to write everything in one line. Everything else is meek.

    • @troybaxter
      @troybaxter Год назад +5

      @@KucheKlizma I agree. You are not a true computer programmer if you aren't condensing your 100,000 line program into one single line.

  • @user-vr2rq5hl6l
    @user-vr2rq5hl6l Месяц назад

    Excellent recommendation! I’ve been doing this for years and it is much more readable!

  • @itsJimpex
    @itsJimpex 7 месяцев назад

    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.

  • @gmikay
    @gmikay Год назад +341

    Swift developers: ok

    • @dosenbiiir
      @dosenbiiir Год назад +15

      Never used swift. Can you explain pls? :D Edit: Ok i read in the comments...Guard :)

    • @Rudxain
      @Rudxain Год назад +7

      @@dosenbiiir Maybe Swift has something similar to Rust's expression matcher (a variant of switch/case)? I guess

    • @dosenbiiir
      @dosenbiiir Год назад +7

      @@Rudxain yeah i think what he means is called Guard in Swift. Some other comments mentioned it here

    • @Rudxain
      @Rudxain Год назад +6

      @@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

    • @dosenbiiir
      @dosenbiiir Год назад +2

      @@Rudxain Yeah I also checked it out now. Nice Feature!😃

  • @acerIOstream
    @acerIOstream Год назад +1295

    I'm just sitting here trying to figure out if you're a québécois based on your accent

    • @FlutterMapp
      @FlutterMapp  Год назад +339

      😂😂 Yep!

    • @lieutenantpepper2734
      @lieutenantpepper2734 Год назад +52

      The accent tells it all

    • @tomr6955
      @tomr6955 Год назад +9

      @@lieutenantpepper2734 no kidding

    • @Mickplouffe
      @Mickplouffe Год назад +22

      Instant Spotted. That is my accent xD

    • @sadmatch41
      @sadmatch41 Год назад +12

      I went in the comment just for that reason 😂

  • @jacoslabbert5928
    @jacoslabbert5928 Год назад +1

    Early return, early exit, negative checking - makes for clean code. 👌

  • @suluntulu
    @suluntulu Месяц назад

    The thing I like about this tip is that it is applicable is almost any coding language

  • @Kaivuri8D
    @Kaivuri8D Год назад +155

    seeAdminPanel as default statement is just wonderful.

    • @OligoST
      @OligoST Год назад +15

      😂 i was thinking it too

    • @Thomas7994
      @Thomas7994 Год назад +3

      Why is it wrong? Not trying to offend, I'm genuinely curious.

    • @OligoST
      @OligoST Год назад +53

      @@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

    • @TsaiAGw
      @TsaiAGw Год назад +10

      enclose it with (wifi && login && admin) just for precaution ?

    • @CM-xr9oq
      @CM-xr9oq Год назад +12

      @@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'.

  • @juliand665
    @juliand665 Год назад +68

    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.

  • @RealEverythingComputers
    @RealEverythingComputers 2 месяца назад

    Awesome approach. Never thought about this. Thank you very much!

  • @gandamraviteja7019
    @gandamraviteja7019 Год назад +1

    Very good explanation buddy very informative thank you for making life easy

  • @wielderXII
    @wielderXII Год назад

    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

  • @SergeDuka
    @SergeDuka Год назад +344

    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).

    • @kameronbriggs235
      @kameronbriggs235 Год назад +4

      nooo... lol get real cmon now.

    • @altkev
      @altkev Год назад +11

      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 😂

    • @SheelByTorn
      @SheelByTorn 11 месяцев назад +1

      pft... JavaScript devs

    • @nobafan7515
      @nobafan7515 7 месяцев назад

      Unless you're OK with slow software.

  • @JohnSmith-ut5th
    @JohnSmith-ut5th Год назад +10

    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.

    • @topcat57691
      @topcat57691 Год назад

      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

  • @IcyPickleYT
    @IcyPickleYT 15 дней назад +1

    You can also remove the brackets and do "return debugprint" on the same line as the condition

  • @OmarAlkhateeb-om7xe
    @OmarAlkhateeb-om7xe Год назад

    One of the best ways that i learnt in C++ before when i was beg,

  • @twerkingfish4029
    @twerkingfish4029 Год назад +82

    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.

    • @KarimTemple
      @KarimTemple Год назад +4

      Advantages like what?

    • @KarimTemple
      @KarimTemple Год назад +3

      @Dave Bieleveld ... like what?

    • @KarimTemple
      @KarimTemple Год назад +4

      @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.

    • @hiperion_1416
      @hiperion_1416 Год назад

      if it works like it should it isnt wrong

    • @KarimTemple
      @KarimTemple Год назад +1

      @@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.

  • @JackBond1234
    @JackBond1234 Год назад +540

    My coworkers insist that it's an even worse sin to have multiple return statements.

    • @civil_leuthie
      @civil_leuthie Год назад +83

      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.

    • @raggebatman
      @raggebatman Год назад +44

      It holds value and contributes to clean code when done right but ultimately it's a matter of preference.

    • @jensenraylight8011
      @jensenraylight8011 Год назад +1

      Your coworker is not Donald Knuth, he's nobody, so he should shut up

    • @Ed.E
      @Ed.E Год назад +17

      It's absolutely not, some people think that but it's literally fine

    • @gianni50725
      @gianni50725 Год назад +60

      then your coworkers are wrong. spaghetti code uses a lot of nested ifs and is totally unreadable because of it.

  • @WS-xd1ph
    @WS-xd1ph Год назад +1

    The default example was way more readable and easier to understand. :)

  • @darrenwalker7343
    @darrenwalker7343 9 месяцев назад +6

    Return early - that technique has been around for decades.

  • @mrclips3939
    @mrclips3939 Год назад +6

    I personally do not like early returns but if the nesting gets that deep I will consider this.

    • @BinGanzLieb
      @BinGanzLieb Год назад

      never heard of DBC?

    • @asfaerfadfasdfsadf5211
      @asfaerfadfasdfsadf5211 Год назад +1

      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')

    • @kjetilhvalstrand1009
      @kjetilhvalstrand1009 19 дней назад

      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.

  • @roygalaasen
    @roygalaasen Год назад +310

    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.

    • @markosaratoga1807
      @markosaratoga1807 Год назад +13

      Exactly my thoughts

    • @tommclean9208
      @tommclean9208 Год назад +68

      and they were so wrong

    • @janisir4529
      @janisir4529 Год назад

      Flow charts are a great way to torture students with, but not particularly useful otherwise.

    • @baka_baca
      @baka_baca Год назад +28

      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.

    • @roygalaasen
      @roygalaasen Год назад +46

      @@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.

  • @xDurdead1
    @xDurdead1 Год назад

    dude feels powerful after taking csc 115

  • @avinandac
    @avinandac 2 месяца назад

    Excellent teaching... More such teaching please ❤

  • @RealCheesyBread
    @RealCheesyBread Год назад +332

    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.

    • @RealCheesyBread
      @RealCheesyBread Год назад +4

      @Ajkl Ajkl 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.

    • @michaelrenper796
      @michaelrenper796 Год назад +7

      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.

    • @1zui
      @1zui Год назад +2

      @@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.

    • @michaelrenper796
      @michaelrenper796 Год назад +21

      @@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.

    • @michaelrenper796
      @michaelrenper796 Год назад +2

      @@1zui PS: If you ike you own "personal preferences" I recommend you give PERL a look.

  • @NicoMoessmer
    @NicoMoessmer Год назад +8

    i love how the "stairs" look like so ill just leave it like that

  • @juhwang79
    @juhwang79 9 месяцев назад +2

    That's good. It can be seen often in linux kernel codes.

  • @blazetronx
    @blazetronx 2 месяца назад

    I’m gonna have to try this out. Merci mon frère!

  • @amamsurri5454
    @amamsurri5454 Год назад +92

    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.

    • @carcasapistacho
      @carcasapistacho Год назад +14

      this is the proper way

    • @ro.gerioj
      @ro.gerioj Год назад +6

      That's it. People forgot about the throw statement.

    • @pikawilliam11
      @pikawilliam11 Год назад

      Switch case can be cool to do here, I think

    • @vacannot
      @vacannot Год назад

      This works but if-else has been proven to not be optimal from a performance perspective

    • @amamsurri5454
      @amamsurri5454 Год назад +5

      @@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

  • @Feuergraf
    @Feuergraf Год назад +154

    De Morgan wants to know your location

  • @silent_7x
    @silent_7x Месяц назад

    bro is saving lives here!

  • @AlberTesla1024
    @AlberTesla1024 28 дней назад

    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."

  • @aidenwinter1117
    @aidenwinter1117 Год назад +18

    I just read it like it's Reddit and it's alright

  • @toastlotl
    @toastlotl Год назад +18

    The RUclips algorithm has sensed that I am learning c# and is ready to tell me all the reasons I suck lmao

  • @bosstareq9
    @bosstareq9 Год назад

    I haven’t learnt this language yet but this tactic is genius!

  • @seanjarrell5198
    @seanjarrell5198 Год назад

    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.

  • @ryh5169
    @ryh5169 Год назад +7

    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.)

    • @Ed.E
      @Ed.E Год назад +2

      I think that's what the debug message function does, but just throw an error if you want a proper stack trace

    • @maik5825
      @maik5825 Год назад +2

      This idea is cool when validating forms or requests.

  • @nadavf24
    @nadavf24 Год назад +119

    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 👍

    • @maxsteffey6521
      @maxsteffey6521 Год назад +89

      The main reason he hasn't is because of the specific error messages for each condition

    • @soyitiel
      @soyitiel Год назад +20

      Also, nothing wrong with multiple early returns

    • @Ruchunteur
      @Ruchunteur Год назад +48

      @@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.

    • @imluctor5997
      @imluctor5997 Год назад +4

      hes just explaing for beginners calm down guys

    • @wattsonthetube
      @wattsonthetube Год назад +2

      @@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.

  • @shobiav3903
    @shobiav3903 11 месяцев назад

    Yes, i have been using this guard clauses technique a lot in my code. It makes the code look less confusing and more readable.
    But after watching this video only i know the name is guard clauses techique.

  • @LV-1969
    @LV-1969 Месяц назад

    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)

  • @Barsay
    @Barsay Год назад +42

    ah yes the "this is always good, this is always bad" technique

    • @omikronweapon
      @omikronweapon Год назад

      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"

  • @sampatsharma2392
    @sampatsharma2392 Год назад +31

    I have been using it for years without knowing the name 😂

  • @Shoeb._.248G
    @Shoeb._.248G 10 месяцев назад

    Thanks bro Ithelped me a lot to make i simpler

  • @user-lg9im2xy5e
    @user-lg9im2xy5e 4 месяца назад

    bro this is the most helpful thing ever

  • @thatGuy-wm2cr
    @thatGuy-wm2cr Год назад +14

    Me with 'elif'
    *laughing maniacally*

    • @kleinebre
      @kleinebre Год назад +1

      "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.

    • @Ethorbit
      @Ethorbit Год назад +6

      @@kleinebre I never understood people interested in micro-optimizations. The performance impact of those extra cycles will be almost impossible to notice.

  • @spe02001
    @spe02001 Год назад +5

    It’s not wrong. It’s just one way to do it. I usually think of how I would further develop the method.

  • @joeterezaboss6801
    @joeterezaboss6801 18 дней назад

    I'm just dumb ,this thing pierced my brain n went through at the speed of light, even tho I'm a beginner in coding aspiring to code 😂😅

  • @marky1756
    @marky1756 4 месяца назад

    Oh I see, I've learned something new today. Ty

  • @ZorMon
    @ZorMon Год назад +16

    You can also use a enum with states (if your language supports enums or similar) and check values a switch block.

  • @markgearing
    @markgearing Год назад +39

    In the next short, we learn the benefits of GOTO.

    • @aadenboy
      @aadenboy Год назад +3

      oh god

    • @P1nkR
      @P1nkR Год назад +3

      I prefer COMEFROM from the Intercal language. It is the same, but worse.

    • @71kimg
      @71kimg Год назад

      Even John Carmack says that we still
      need a GOTO statement.

  • @nealmarlin4949
    @nealmarlin4949 11 месяцев назад +1

    We commonly call it protective programing. The language like Swift even makes it as language feature.

  • @RavenMobile
    @RavenMobile 4 часа назад

    I naturally came to the conclusion that many levels of nested ifs are hard to read. I usually come up with various ways around it.
    In general I try to keep my coding to 80 columns or less, and I use 3 spaces for indenting.

  • @N30ZUK1
    @N30ZUK1 Год назад +28

    Code scuffed from nesting? Scuff it instead with short-circuiting! (Protip: restructure code instead of doing this)

    • @dmurvihill
      @dmurvihill 6 месяцев назад

      Finally, a reasonable take.

    • @shyshka_
      @shyshka_ 4 месяца назад +2

      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

    • @FormlessFlesh
      @FormlessFlesh Месяц назад

      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).

  • @kylekeenan3485
    @kylekeenan3485 Год назад +33

    In this example I would have added an && clause if using C#...
    If (wifi && login && admin)
    {
    SeeAdminPanel();
    }
    Else
    {
    Report an error string...
    Return;
    }

    • @artemetra3262
      @artemetra3262 Год назад +12

      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

    • @gianni50725
      @gianni50725 Год назад +1

      @@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.

    • @Kaivuri8D
      @Kaivuri8D Год назад

      @@kylekeenan3485 Oh my god, never ever do this

    • @troybaxter
      @troybaxter Год назад +5

      @@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.

    • @troybaxter
      @troybaxter Год назад +2

      @dino dina I wouldn’t say yuck. Just centralizes warnings and alerts. It really helps with readability and quickly understanding what went wrong.

  • @a_rod1678
    @a_rod1678 Год назад

    This will help with my Sonarqube issues

  • @OneIdeaTooMany
    @OneIdeaTooMany 3 месяца назад

    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.

  • @dylanf3108
    @dylanf3108 Год назад +22

    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.

    • @soniablanche5672
      @soniablanche5672 Год назад +2

      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.

    • @asdfxyz_randomname2133
      @asdfxyz_randomname2133 Год назад

      ​@@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.

    • @RadixTheTroll
      @RadixTheTroll Год назад +8

      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.

    • @dylanf3108
      @dylanf3108 Год назад

      @@RadixTheTroll Cool. That works well for me.

    • @AntiAtheismIsUnstoppable
      @AntiAtheismIsUnstoppable Год назад

      @@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.

  • @Ria_NT
    @Ria_NT Год назад +14

    damn, how come I only saw this after I submitted 1000 unhealthy lines of code to my professor...

    • @kekagiso
      @kekagiso Год назад +3

      It's a good thing you didn't see this, this is "asking for trouble" code...

  • @drenifelmain
    @drenifelmain Год назад

    Thank you! I am still learning

  • @lainwired3946
    @lainwired3946 9 месяцев назад

    Its not always wrong, and usually, this is exactly what the compiler or interpreter unrolls a lot of this to anyway, to optimize. Be as readable as possible but dont try and over optimise as ususoly youll end uo slower becayse the compiler doesnt expect it. You didnt actually say it was slow to be fair and im glad you didnt make a switch!

  • @mikezheng33
    @mikezheng33 Год назад +6

    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.

  • @reinux
    @reinux Год назад +4

    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.

  • @rob7xiv
    @rob7xiv Год назад

    In php you can throw Exceptions or die(), that helped my code much, thx .

  • @enoq98
    @enoq98 Год назад +1

    For some things you could use await too

  • @MizuFelix
    @MizuFelix 2 месяца назад +6

    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.

  • @HolyGarbage
    @HolyGarbage Год назад +22

    I call this the "precondition pattern"

  • @vanlepthien6768
    @vanlepthien6768 Год назад

    This works for some situations (like this contrived example), but doesn't if both alternatives actually do something. Deep nesting of If statements will make things hard to read, but reasonable use can make logic more obvious.

  • @Alchemist10241
    @Alchemist10241 Год назад

    This technique is incredibly useful

  • @patrickalexanderlucasvande4214
    @patrickalexanderlucasvande4214 Год назад +5

    So just negate the whole function love it

  • @britisheastindiacompany2951
    @britisheastindiacompany2951 Год назад +5

    my dumb brain assuming that it was going to be changed to elseifs

    • @vorpal22
      @vorpal22 Год назад +2

      ...which is a much better way of doing things.

  • @nerosonic
    @nerosonic Год назад

    Thanks for sharing!

  • @That_0ne_Dev
    @That_0ne_Dev 3 месяца назад

    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.

  • @powertomato
    @powertomato Год назад +8

    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.

    • @friedec3622
      @friedec3622 Год назад

      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.

  • @kiritokun2962
    @kiritokun2962 Год назад +45

    i always do this because its cleaner, readable and i love it 😁

    • @sidneymonteiro3670
      @sidneymonteiro3670 Год назад

      I would fire your ass for this bs.

    • @Brukrex
      @Brukrex Год назад +1

      I love you

    • @raed9152
      @raed9152 Год назад

      @@Brukrex I love your mom

    • @orkhepaj
      @orkhepaj Год назад +1

      but it is not

    • @vorpal22
      @vorpal22 Год назад

      @@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.

  • @leon_De_Grelle
    @leon_De_Grelle Год назад +1

    This is short, helpful advice to new programmers. I have been programming since age 12 - for approx 27 years - in C, BASIC, PHP, C#, and even languages without ifs (like x86 assembler) and I use this. I did not know it was called "guarded clause" but I like knowing the name of it. Thank you!

  • @therealsuper5828
    @therealsuper5828 5 месяцев назад

    good explanation!

  • @JohnDoe19991
    @JohnDoe19991 Год назад +27

    and operator be like : am I a joke to you

    • @muhanad102
      @muhanad102 Год назад +4

      There are a different message for each if ... Also this is an example to show you how you can utilize return instead of nesting ifs

  • @StrangerOnTheWeb
    @StrangerOnTheWeb Год назад +76

    Someone send this to Yandere dev

    • @doriondouglas6176
      @doriondouglas6176 Год назад +4

      why doesnt that man just use switches. he's in Unity is he not???

    • @sony17209
      @sony17209 Год назад +2

      @@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.

    • @BlueProgamer212
      @BlueProgamer212 Год назад +2

      ​@@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.

    • @asi3136
      @asi3136 9 месяцев назад

      ​@@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

  • @user-du7sd5zg9f
    @user-du7sd5zg9f Год назад

    Its actually useful in some areas. It is possible to bypass one if conditions using fault injection.

  • @gxanlvxgx8443
    @gxanlvxgx8443 3 месяца назад +1

    Bellissimo video!