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

Sdílet
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

Komentáře • 3,3K

  • @diegovera6858
    @diegovera6858 Před rokem +13066

    Ahhh yes. The "early return" technique.

    • @TheRealZitroX
      @TheRealZitroX Před rokem +285

      Not bad tho

    • @johnbrooks5903
      @johnbrooks5903 Před rokem +1083

      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 Před rokem +280

      @@johnbrooks5903 goto is a babe tho

    • @daanhoek1818
      @daanhoek1818 Před rokem +621

      @@sleaf6 uses goto☠️☠️☠️

    • @notRealCapedBaldy
      @notRealCapedBaldy Před rokem +298

      @@sleaf6 spaghetti code incoming 😬

  • @sb_dunk
    @sb_dunk Před rokem +7674

    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 Před rokem +419

      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 Před rokem +113

      ​@@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 Před rokem +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 Před rokem +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 Před rokem +13

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

  • @user-vu8fm5vb4n
    @user-vu8fm5vb4n Před rokem +1947

    "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 Před rokem +96

      Flutter left the chat.

    • @arsikkbar
      @arsikkbar Před rokem +65

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

    • @rya3190
      @rya3190 Před 5 měsíci +24

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

    • @CrazycatASG
      @CrazycatASG Před 5 měsíci +6

      linus speaks for me 🗣️🗣️🗣️

    • @Lintee_Second
      @Lintee_Second Před 5 měsíci +4

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

  • @crewrangergaming9582
    @crewrangergaming9582 Před rokem +5485

    The "AND" operator has left the chat.

    • @xLAMCHOPPED
      @xLAMCHOPPED Před rokem +747

      AND operator wouldn't fix the problem in this example

    • @crewrangergaming9582
      @crewrangergaming9582 Před rokem +345

      ​@@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 Před rokem +44

      How tf would it help?

    • @mister_hamana
      @mister_hamana Před rokem +397

      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 Před rokem +607

      “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 Před rokem +7555

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

    • @spoopyscaryskelebones3846
      @spoopyscaryskelebones3846 Před rokem +95

      Woah

    • @________________404
      @________________404 Před rokem +447

      Imagine if you have faulty unit tests in the whole codebase

    • @michaelrenper796
      @michaelrenper796 Před rokem +264

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

    • @epicgameryt4052
      @epicgameryt4052 Před rokem +209

      Just imagine if you make everyone admin. Everyone becomes admin

    • @fennecbesixdouze1794
      @fennecbesixdouze1794 Před rokem +181

      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.

  • @mikezheng33
    @mikezheng33 Před rokem +1971

    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 Před rokem +282

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

    • @Carhill
      @Carhill Před rokem +41

      Well that escalated quickly.

    • @Kanal-yh5xi
      @Kanal-yh5xi Před rokem +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 Před rokem +157

      @@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 Před rokem +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.

  • @Chevifier
    @Chevifier Před 6 měsíci +31

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

    • @ShivamJha00
      @ShivamJha00 Před 2 měsíci

      It's a frontend code though

    • @ParasGupta-ce9bj
      @ParasGupta-ce9bj Před 11 dny

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

  • @zsi
    @zsi Před rokem +798

    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 Před rokem +74

      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 Před rokem +63

      @윤형석 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 Před rokem +10

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

    • @rishi_rajani
      @rishi_rajani Před rokem +6

      I like the analogy😂

    • @primer6714
      @primer6714 Před rokem +1

      😂

  • @davidfreer2166
    @davidfreer2166 Před rokem +1031

    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 Před rokem +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 Před rokem +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 Před rokem +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 Před rokem +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 Před rokem +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

  • @samsonwu9378
    @samsonwu9378 Před rokem +724

    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 Před rokem +23

      Why not just separate the calculation into a separate function?

    • @rosiefay7283
      @rosiefay7283 Před rokem +86

      @@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 Před rokem +71

      @@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 Před rokem +10

      Now I want to see what the function was

    • @veritasliberabitvos454
      @veritasliberabitvos454 Před rokem +42

      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.

  • @notagamer8782
    @notagamer8782 Před 8 měsíci +9

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

  • @MizuFelix
    @MizuFelix Před 2 měsíci +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.

  • @oblivioncth
    @oblivioncth Před rokem +909

    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 Před rokem +101

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

    • @wlt3585
      @wlt3585 Před rokem +247

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

    • @dionisietarlev7081
      @dionisietarlev7081 Před rokem +36

      @@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 Před rokem +101

      @@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 Před rokem +18

      @@artificiallyunintelligent4537 xD Profs are easily in the

  • @xrayian
    @xrayian Před rokem +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 Před rokem +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 Před rokem +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 Před rokem +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 Před rokem +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 Před rokem +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.

  • @cryptic_daemon_
    @cryptic_daemon_ Před rokem +58

    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 Před rokem +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_ Před 4 měsíci +5

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

    • @theConcernedWyvern
      @theConcernedWyvern Před měsícem

      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 Před 28 dny

      ​@@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 Před 27 dny

      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.

  • @RandomYouTubevids-bl7sc
    @RandomYouTubevids-bl7sc Před 6 měsíci +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

  • @bluealteran4599
    @bluealteran4599 Před rokem +183

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

    • @guerra_dos_bichos
      @guerra_dos_bichos Před rokem +7

      do people use it?

    • @D0Samp
      @D0Samp Před rokem +6

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

    • @bluealteran4599
      @bluealteran4599 Před rokem +11

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

    • @xybersurfer
      @xybersurfer Před rokem +1

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

    • @nickwallette6201
      @nickwallette6201 Před rokem +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.

  • @tychozzyx9439
    @tychozzyx9439 Před rokem +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 Před rokem +1

      Else if works not in this example

    • @tychozzyx9439
      @tychozzyx9439 Před rokem +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 Před rokem +16

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

    • @quandaviousvonheadsonzingl6453
      @quandaviousvonheadsonzingl6453 Před rokem +2

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

    • @Crecross
      @Crecross Před 8 měsíci

      ​@@tychozzyx9439nerd

  • @rax7223
    @rax7223 Před 28 dny

    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

  • @itsJimpex
    @itsJimpex Před 7 měsíci

    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.

  • @RealCheesyBread
    @RealCheesyBread Před rokem +331

    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.

    • @Winter_Wyvern1
      @Winter_Wyvern1 Před rokem +9

      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.

    • @RealCheesyBread
      @RealCheesyBread Před rokem +4

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

    • @michaelrenper796
      @michaelrenper796 Před rokem +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 Před rokem +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 Před rokem +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.

  • @garrafote18
    @garrafote18 Před rokem +110

    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 Před rokem +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 Před rokem +1

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

    • @troybaxter
      @troybaxter Před rokem +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.

  • @CodeTom
    @CodeTom Před 2 hodinami

    Bro this is so helpful. I really Appreciate it!

  • @gmikay
    @gmikay Před rokem +341

    Swift developers: ok

    • @dosenbiiir
      @dosenbiiir Před rokem +15

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

    • @Rudxain
      @Rudxain Před rokem +7

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

    • @dosenbiiir
      @dosenbiiir Před rokem +7

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

    • @Rudxain
      @Rudxain Před rokem +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 Před rokem +2

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

  • @acerIOstream
    @acerIOstream Před rokem +1295

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

  • @eugenecbell
    @eugenecbell Před 6 měsíci

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

  • @IcyPickleYT
    @IcyPickleYT Před 3 dny +1

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

  • @SergeDuka
    @SergeDuka Před rokem +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 Před rokem +4

      nooo... lol get real cmon now.

    • @altkev
      @altkev Před rokem +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 Před 10 měsíci +1

      pft... JavaScript devs

    • @nobafan7515
      @nobafan7515 Před 7 měsíci

      Unless you're OK with slow software.

  • @Kaivuri8D
    @Kaivuri8D Před rokem +155

    seeAdminPanel as default statement is just wonderful.

    • @OligoST
      @OligoST Před rokem +15

      😂 i was thinking it too

    • @Thomas7994
      @Thomas7994 Před rokem +3

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

    • @OligoST
      @OligoST Před rokem +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 Před rokem +10

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

    • @CM-xr9oq
      @CM-xr9oq Před rokem +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'.

  • @LV-1969
    @LV-1969 Před 28 dny

    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)

  • @darrenwalker7343
    @darrenwalker7343 Před 9 měsíci +6

    Return early - that technique has been around for decades.

  • @JackBond1234
    @JackBond1234 Před rokem +539

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

    • @civil_leuthie
      @civil_leuthie Před rokem +82

      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 Před rokem +42

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

    • @jensenraylight8011
      @jensenraylight8011 Před rokem +1

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

    • @Ed.E
      @Ed.E Před rokem +16

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

    • @gianni50725
      @gianni50725 Před rokem +59

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

  • @twerkingfish4029
    @twerkingfish4029 Před rokem +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 Před rokem +4

      Advantages like what?

    • @KarimTemple
      @KarimTemple Před rokem +3

      @Dave Bieleveld ... like what?

    • @KarimTemple
      @KarimTemple Před rokem +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 Před rokem

      if it works like it should it isnt wrong

    • @KarimTemple
      @KarimTemple Před rokem +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.

  • @StrangerOnTheWeb
    @StrangerOnTheWeb Před rokem +76

    Someone send this to Yandere dev

    • @doriondouglas6176
      @doriondouglas6176 Před rokem +4

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

    • @sony17209
      @sony17209 Před 11 měsíci +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 Před 11 měsíci +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 Před 8 měsíci

      ​@@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-vr2rq5hl6l
    @user-vr2rq5hl6l Před měsícem

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

  • @JohnSmith-ut5th
    @JohnSmith-ut5th Před rokem +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 Před rokem

      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

  • @roygalaasen
    @roygalaasen Před rokem +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 Před rokem +13

      Exactly my thoughts

    • @tommclean9208
      @tommclean9208 Před rokem +68

      and they were so wrong

    • @janisir4529
      @janisir4529 Před rokem

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

    • @baka_baca
      @baka_baca Před rokem +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 Před rokem +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.

  • @OneIdeaTooMany
    @OneIdeaTooMany Před 2 měsíci

    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.

  • @N30ZUK1
    @N30ZUK1 Před rokem +26

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

    • @dmurvihill
      @dmurvihill Před 6 měsíci

      Finally, a reasonable take.

    • @shyshka_
      @shyshka_ Před 4 měsíci +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 Před 18 dny

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

  • @amamsurri5454
    @amamsurri5454 Před rokem +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 Před rokem +14

      this is the proper way

    • @ro.gerioj
      @ro.gerioj Před rokem +6

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

    • @pikawilliam11
      @pikawilliam11 Před rokem

      Switch case can be cool to do here, I think

    • @vacannot
      @vacannot Před rokem

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

    • @amamsurri5454
      @amamsurri5454 Před rokem +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

  • @nadavf24
    @nadavf24 Před rokem +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 Před rokem +89

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

    • @soyitiel
      @soyitiel Před rokem +20

      Also, nothing wrong with multiple early returns

    • @Ruchunteur
      @Ruchunteur Před rokem +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 Před rokem +4

      hes just explaing for beginners calm down guys

    • @wattsonthetube
      @wattsonthetube Před rokem +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.

  • @suluntulu
    @suluntulu Před měsícem

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

  • @seanjarrell5198
    @seanjarrell5198 Před rokem

    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.

  • @juliand665
    @juliand665 Před rokem +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.

  • @mrclips3939
    @mrclips3939 Před rokem +6

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

    • @BinGanzLieb
      @BinGanzLieb Před rokem

      never heard of DBC?

    • @asfaerfadfasdfsadf5211
      @asfaerfadfasdfsadf5211 Před rokem +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 Před 7 dny

      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.

  • @wielderXII
    @wielderXII Před rokem

    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

  • @juhwang79
    @juhwang79 Před 8 měsíci +2

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

  • @nealmarlin4949
    @nealmarlin4949 Před 10 měsíci +1

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

  • @Feuergraf
    @Feuergraf Před rokem +155

    De Morgan wants to know your location

  • @NicoMoessmer
    @NicoMoessmer Před rokem +8

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

  • @nerosonic
    @nerosonic Před rokem

    Thanks for sharing!

  • @gandamraviteja7019
    @gandamraviteja7019 Před 11 měsíci +1

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

  • @aidenwinter1117
    @aidenwinter1117 Před rokem +18

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

  • @ryh5169
    @ryh5169 Před rokem +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 Před rokem +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 Před rokem +2

      This idea is cool when validating forms or requests.

  • @RealEverythingComputers
    @RealEverythingComputers Před měsícem

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

  • @allcapsone7809
    @allcapsone7809 Před rokem +2

    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.

  • @kylekeenan3485
    @kylekeenan3485 Před rokem +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 Před rokem +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 Před rokem +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 Před rokem

      @@kylekeenan3485 Oh my god, never ever do this

    • @troybaxter
      @troybaxter Před rokem +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 Před rokem +2

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

  • @powertomato
    @powertomato Před rokem +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 Před rokem

      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.

  • @brianm.johnson4438
    @brianm.johnson4438 Před rokem +1

    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.

    • @doomse150
      @doomse150 Před rokem +1

      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.

  • @adriendecroy7254
    @adriendecroy7254 Před rokem +29

    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.

    • @SheelByTorn
      @SheelByTorn Před 10 měsíci +7

      if this is harder for you to understand you probably haven't code a lot

    • @adriendecroy7254
      @adriendecroy7254 Před 10 měsíci

      @@SheelByTorn 30 years, and very successfully. My own development company. So I speak from experience. How about you?

    • @k0d4xbl1xy4
      @k0d4xbl1xy4 Před 9 měsíci

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

    • @samuraijosh1595
      @samuraijosh1595 Před 4 měsíci

      This is how a Haskeller would structure the logic using guards. You need to code more.

  • @ZorMon
    @ZorMon Před rokem +16

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

  • @markgearing
    @markgearing Před rokem +39

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

    • @aadenboy
      @aadenboy Před rokem +3

      oh god

    • @P1nkR
      @P1nkR Před rokem +3

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

    • @71kimg
      @71kimg Před rokem

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

  • @silent_7x
    @silent_7x Před 28 dny

    bro is saving lives here!

  • @drenifelmain
    @drenifelmain Před rokem

    Thank you! I am still learning

  • @sampatsharma2392
    @sampatsharma2392 Před rokem +31

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

  • @HolyGarbage
    @HolyGarbage Před rokem +22

    I call this the "precondition pattern"

  • @tycameron1836
    @tycameron1836 Před 17 dny

    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.

  • @alikia2x
    @alikia2x Před rokem +1

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

    • @kjetilhvalstrand1009
      @kjetilhvalstrand1009 Před 7 dny +1

      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?

  • @spe02001
    @spe02001 Před rokem +5

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

  • @dylanf3108
    @dylanf3108 Před rokem +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 Před rokem +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 Před rokem

      ​@@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 Před rokem +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 Před rokem

      @@RadixTheTroll Cool. That works well for me.

    • @AntiAtheismIsUnstoppable
      @AntiAtheismIsUnstoppable Před rokem

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

  • @AlberTesla1024
    @AlberTesla1024 Před 16 dny

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

  • @jacoslabbert5928
    @jacoslabbert5928 Před rokem +1

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

  • @Ria_NT
    @Ria_NT Před rokem +14

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

    • @kekagiso
      @kekagiso Před rokem +3

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

  • @Barsay
    @Barsay Před rokem +42

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

    • @omikronweapon
      @omikronweapon Před rokem

      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"

  • @Canilho
    @Canilho Před rokem +5

    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.

  • @OmarAlkhateeb-om7xe
    @OmarAlkhateeb-om7xe Před rokem

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

  • @reinux
    @reinux Před rokem +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.

  • @thatGuy-wm2cr
    @thatGuy-wm2cr Před rokem +14

    Me with 'elif'
    *laughing maniacally*

    • @kleinebre
      @kleinebre Před rokem +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 Před rokem +6

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

  • @TheBaljitSingh
    @TheBaljitSingh Před 2 měsíci

    that's great idea dude

  • @bob23j95
    @bob23j95 Před rokem +44

    Binary operators have left the chat

    • @isma92
      @isma92 Před rokem +6

      the thing is I think he wants to log a different error message depending on the condition

    • @cool-aquarian
      @cool-aquarian Před rokem

      next video from this channel:
      Binary operators are bad for readability.

    • @adeptfelix
      @adeptfelix Před rokem

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

  • @mikezheng33
    @mikezheng33 Před rokem +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.

  • @kiritokun2962
    @kiritokun2962 Před rokem +45

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

    • @sidneymonteiro3670
      @sidneymonteiro3670 Před rokem

      I would fire your ass for this bs.

    • @Brukrex
      @Brukrex Před rokem +1

      I love you

    • @raed9152
      @raed9152 Před rokem

      @@Brukrex I love your mom

    • @orkhepaj
      @orkhepaj Před rokem +1

      but it is not

    • @vorpal22
      @vorpal22 Před rokem

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

  • @gxanlvxgx8443
    @gxanlvxgx8443 Před 3 měsíci +1

    Bellissimo video!

  • @adityag6022
    @adityag6022 Před rokem

    This is really useful. Thank you

    • @kameronbriggs235
      @kameronbriggs235 Před rokem

      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 */ );
      }

  • @maniek86
    @maniek86 Před rokem +39

    Me being real programmer: goto statement

    • @Rhidayah
      @Rhidayah Před 11 měsíci +13

      Segmentation Fault be like: 🗿

    • @spookycode
      @spookycode Před 3 měsíci

      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

  • @patrickalexanderlucasvande4214

    So just negate the whole function love it

  • @Iwitrag
    @Iwitrag Před rokem

    These shorts are super useful

  • @enoq98
    @enoq98 Před rokem +1

    For some things you could use await too

  • @andrewbrown864
    @andrewbrown864 Před rokem +14

    I didn’t realize there was a name for that

    • @Adroitbit
      @Adroitbit Před rokem

      Me too 💪🗿👍

    • @LinkEX
      @LinkEX Před rokem

      Gladly there's a name for pretty much every pattern :D

  • @LoZander
    @LoZander Před rokem +3

    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

  • @avinandac
    @avinandac Před 2 měsíci

    Excellent teaching... More such teaching please ❤

  • @blazetronx
    @blazetronx Před 2 měsíci

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

  • @tylerholden1548
    @tylerholden1548 Před rokem +7

    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.

  • @cc_par
    @cc_par Před rokem +89

    software developers are hardcore gatekeepers, change my mind.

    • @MonkeyBoyKHS
      @MonkeyBoyKHS Před rokem

      You're clearly new here. Maybe brush up a little more before commenting, skid.

    • @MonkeyBoyKHS
      @MonkeyBoyKHS Před rokem +5

      @@cc_par welcome to the joke how may I take your order

    • @cc_par
      @cc_par Před rokem +8

      @@MonkeyBoyKHS pathetic.

    • @nallid7357
      @nallid7357 Před rokem +3

      Program with me and I'll change your mind to "most software developers..."

    • @SteamShinobi
      @SteamShinobi Před rokem +3

      ​@@nallid7357 well clearly not a mathematician lmao; you are not "most" as a single programmer.

  • @marcinml6537
    @marcinml6537 Před 2 dny

    It is just good way to exception and exit conditions handling

  • @Shoeb._.248G
    @Shoeb._.248G Před 10 měsíci

    Thanks bro Ithelped me a lot to make i simpler

  • @rcronk
    @rcronk Před rokem +18

    One entry, one exit works better. They figured that out 40 years ago.

    • @BasketOfPuppies
      @BasketOfPuppies Před 8 měsíci +2

      And we moved on from that close to 40 years ago. Returning early is a general best practice for a long, long time.

    • @rcronk
      @rcronk Před 8 měsíci +1

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

    • @youtubeenjoyer1743
      @youtubeenjoyer1743 Před 3 měsíci

      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

  • @toastlotl
    @toastlotl Před rokem +18

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

  • @WS-xd1ph
    @WS-xd1ph Před rokem +1

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

  • @That_0ne_Dev
    @That_0ne_Dev Před 2 měsíci

    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.