Why I Don't Use Else When Programming

Sdílet
Vložit
  • čas přidán 2. 06. 2024
  • Nick Chapsas's Video: • Why I don't use the "e...
    This may sound crazy but I really don't use the else keyword in my programming anymore. When I do end up using else it usually leads to worse code than if I purposely avoided it. In this video I explain exactly why that is.
    📚 Materials/References:
    Optional Chaining Video: • 5 Must Know JavaScript...
    Optional Chaining Article: blog.webdevsimplified.com/202...
    Guard Clause Article: blog.webdevsimplified.com/202...
    🌎 Find Me Here:
    My Blog: blog.webdevsimplified.com
    My Courses: courses.webdevsimplified.com
    Patreon: / webdevsimplified
    Twitter: / devsimplified
    Discord: / discord
    GitHub: github.com/WebDevSimplified
    CodePen: codepen.io/WebDevSimplified
    ⏱️ Timestamps:
    00:00 - Introduction
    01:00 - Guard Clauses
    04:03 - Single Return Is Bad
    05:43 - Extract Functions
    #StopUsingElse #WDS #JavaScript

Komentáře • 4,1K

  • @WebDevSimplified
    @WebDevSimplified  Před 3 lety +255

    You may have already seen Nick Chapsas's video on this same topic but if not you should check it out. czcams.com/video/_ougvb8mT7k/video.html
    His video was the inspiration for me creating this video as I loved what he had to say and wanted to add my own thoughts to the conversation.

    • @larsdepauw2484
      @larsdepauw2484 Před 3 lety +5

      It's funny. CZcams recommended me one of your CSS battle videos, which led to being suggested more of your channel, which led to being recommended Nick's channel. Saw his vid on the else keyword too, feels like such a small world haha

    • @agon19
      @agon19 Před 3 lety

      Just the other day I was talking with my girlfriend about Nick's video!

    • @nilkanthambatkar9980
      @nilkanthambatkar9980 Před 3 lety

      Will you make a tutorial on game development

    • @anshjain9293
      @anshjain9293 Před 3 lety +2

      How are you using those emogies in code

    • @cai0
      @cai0 Před 3 lety +4

      @@anshjain9293 do you use Win10? If so, Windows Key + . (dot)

  • @cod3r1337
    @cod3r1337 Před 2 lety +3062

    Take it from someone with close to 15 years of experience in multiple programming languages and styles: Always take advice like this with a grain of salt. Yes, "else" hurts readability *when used ineffectively* (mostly with long statement bocks, which obviously is bad), and sometimes early exit is preferable, or even more modern idioms like switch expressions if your language supports it (JS sadly doesn't). BUT in many cases it's much clearer and simpler to just use traditional if-else. If the statement blocks are both just a single line each, with nothing else going on in the function other than a single pair of if-else statements, then there's absolutely nothing wrong with it. If, on the other hand, the else keyword is hidden after pages of scrolling down, you have a complete mess, and it's high time to refactor your function and at the very least split it up into smaller functions - and early return won't save you in that case, it may in fact make things even worse. Obviously, be sure to have decent test coverage before you refactor.
    Just use the idiom that conveys the semantics you intend to convey in whatever idiom feels most natural for the job at hand. More often than not, if-else does just that. It's always a matter of context. The important part is to take a moment or two to think about it rather than mindlessly applying whatever idiom someone on the internet told you to be the one and only true path. And if in doubt, ask a collegue for a review.
    If the statement were phrased like "Don't use else SO MUCH", now that would be something I could get behind.

    • @minerscale
      @minerscale Před 2 lety +59

      switch case statements are modern huh? Terry A. Davis would be so proud.

    • @cod3r1337
      @cod3r1337 Před 2 lety +27

      @@minerscale By the way, I *do* hope you know the difference between expressions and statements, at least if you call yourself a professional programmer

    • @minerscale
      @minerscale Před 2 lety +28

      @@cod3r1337 I thankfully do not call myself a professional programmer. I'm just a hobbyist doing a music degree. As for the difference between expressions and statements, having just looked it up I think I have a decent understanding of the underlying concept that expressions evaluate to a value whist statements do side effects, and that expressions are inherently safer because the flow of data is more clear, but I don't think I ever put proper words to it, as I lack a comp sci degree or anything of the sort.
      Is it incorrect to call a switch a statement?

    • @heartflame503
      @heartflame503 Před 2 lety +10

      LOL also comments help quite a bit to explain the function ;-)

    • @cod3r1337
      @cod3r1337 Před 2 lety +44

      @@minerscale First off, if your are a hobbyist it's fine if you don't know all the theoretical basics. I happen to be a hobby musician and don't know much about musical theory either. Just try not to wave your lack of knowledge around like a badge of honour. You are just going to piss people off for no good reason.
      Your understanding of expressions is halfway correct, but the actual definition is more limited. Expressions can have side effects just like statements, the difference is just that they evaluate to a value. Most mainstream languages have no way of guaranteeing an expression to be "pure" (side-effect free); some FP languages do, but those are hardly mainstream (sadly, one might argue). Still, it's generally considered good practice even when coding in a non-FP style to avoid side effects in expressions, or at least make them as explicit as possible.
      As for your question: It's absolutely correct to call switch a statement, but in most modern languages it can also be an expression. This allows for some constructs that are much more concise than the traditional statement style. C# has had this feature for quite some time now, Java has finally added it recently, most newer (and even a few older) languages have had it from day one. Some of the major examples that (to my knowledge) still *don't+ have this feature are JS (including TypeScript), C and C++.

  • @yamogebrewold8620
    @yamogebrewold8620 Před 3 lety +2447

    I would say: "I very rarely use else". But there are some cases where an else statement is the only thing that makes sense, and it doesn't hurt readability.

    • @smt4090
      @smt4090 Před 3 lety +25

      So what about this:
      x = random(1,3)
      if x == 1 then
      print("E")
      else
      print("notE")
      ...instead of this
      x = random(1,3)
      if x == 1 then
      print("E1")
      elseif x == 2 then
      print("E2")
      elseif x == 3 then
      *_spontaneous combustion_*

    • @xadielplasencia3674
      @xadielplasencia3674 Před 3 lety +120

      @@smt4090 What about it?

    • @m5a1stuart83
      @m5a1stuart83 Před 3 lety +70

      @@smt4090 else if is built in every programming language. You will use it sometime like it or not.

    • @hangmingzhang5067
      @hangmingzhang5067 Před 3 lety +19

      @@smt4090 i dont know coding etiquette as i have none, but the first one can return in the if so you would need the else assuming you can write it in a function. The second one can be made into a switch case.

    • @Ellisscg
      @Ellisscg Před 3 lety +7

      For me I only ever use a one level ELSE

  • @spacelem
    @spacelem Před 2 lety +363

    I can understand replacing the initial if (not null) that covers everything (early returns are great), but what you've ended up with here is instead of one function which is pretty easy to follow, you've got two functions and the logic is now bouncing all over the place, it's spaghetti code. As the complexity of your functions increase, and you have more variables to keep track of, you'll find yourself building functions with longer signatures and passing stuff all round the place, and it's going to end up very unmaintainable.
    Also elses help you to understand the flow, and signify when you have a number of mutually exclusive cases, whereas a bunch of ifs don't really give you that same information.
    I can definitely see the value of considering whether an else is necessary, but I think here you've half improved the code, and half made it worse.

    • @bryede
      @bryede Před 2 lety +26

      That's what I thought. Bail out early to showcase which cases will not be handled, but a function needing a function simply to avoid an else statement makes no sense. You could do the same thing inline and save making the reader scroll around and the associated stack activity.

    • @Disatiere
      @Disatiere Před 2 lety +9

      See the thing is....
      console.log(validateAge())
      function validateAge(expr)
      {
      switch (expr) {
      case 1:
      return "can drink"
      case 2:
      return "can not drink"
      case 3:
      return "egg"
      default:
      return "Huh???"
      }
      }

    • @shacharh5470
      @shacharh5470 Před 2 lety +14

      That's not what spaggheti code means. Also, making your code more modular usually makes it more maintainable, not less

    • @Disatiere
      @Disatiere Před 2 lety +10

      @Jan Krynicky This shit iis how you end up with a main file that does nothing but load like 1000 lines of internal files that all are just helper functions
      What could go wrong

    • @NickDanger3
      @NickDanger3 Před 2 lety +11

      Having a second function is not “spaghetti code“ at all! You don’t know what the term means

  • @samkroes4611
    @samkroes4611 Před 2 lety +127

    I really appreciate all the comments on this video. It is a huge help to me as a beginner to hear everyone's different opinions. You all rock! 🤘

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

      Here's another perception. The conditional is already done in the ( age < 21), the less than, equal to, greater than operators are already conditional checks, adding in the "if" statement is an extra conditional check.
      The boolean operator will already evaulate to a 0 or 1, which can be used to multiply with the string.
      If you multiply the string by 0, it will be "" blank, if you multiply by 1, it will be the string once.
      Console.Log("No" * (age < 18) + "Maybe" * (age >= 18 && age < 21) + "Yes" * (age >= 21));
      Now you completely removed the extra comparisons. That's branchless programming.

    • @Qewbicle
      @Qewbicle Před 7 měsíci +1

      Note, branchless programming is not always faster, but it's worth being aware. czcams.com/video/bVJ-mWWL7cE/video.html

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

      Just remember the 'web dev' is a new concept and we all USED to actually work on the actual computer without as many abstractions.

  • @UninstallingWindows
    @UninstallingWindows Před 3 lety +1699

    One thing that throws me off sometimes are functions that suggest a boolean return but don't actually return boolean. E.g canDrink suggests true or false return, but it returns undefined or string.

    • @pranavsetpal
      @pranavsetpal Před 3 lety +39

      True, can't really defend against that but in a way you could consider that function as a boolean with edited returns since it is giving a Yes/No answer, except for Not in the US part in this example. I like your name btw, can't wait to do that when my own laptop

    • @JBuchmann
      @JBuchmann Před 3 lety +94

      In such a case I think the best thing to make the code cleaner is to change the function name so that it doesn't imply a boolean return. Function names starting with "is" and "has" should probably return a boolean.

    • @ragnarok7976
      @ragnarok7976 Před 3 lety +20

      I agree with the general point I just don't think it matters all that much in this context. It's just a small example and even without the explanation it's pretty clear what the code is actually doing in its entirety. The code won't be published and the function won't ever be used for the result it produces or doesn't produce.

    • @noahsmith2555
      @noahsmith2555 Před 3 lety +11

      Totally agree

    • @mrmoinn
      @mrmoinn Před 3 lety +45

      That's why I can't live without strongly typed languages. Not only do you have the ability to check the type that is returned by all the functions because it's checked and enforced at compile time, but it's also possible to have dynamic returns that aren't bools by, for example in C#, creating a special enumeration (enum, does JavaScript have it?) type just for that functions return. That way even if the return isn't true or false you can easily tell what all the options are.

  • @bernardoquina3047
    @bernardoquina3047 Před 3 lety +1965

    Moral of the story: Go home early whenever possible!

  • @LCTesla
    @LCTesla Před rokem +21

    The downside of early returning / continuing / breaking is that you can't tell by the IF's condition itself whether your code below it is going to trigger or not. You have to inspect the entire IF block for return / continue /break statements to find out if your code below is in a "virtual" else block or not.

  • @theotimefasquelle3561
    @theotimefasquelle3561 Před rokem +140

    The version shown at 6:35 is the most readable IMO and the one I would write. I find the final solution way less easy to read because of the unnecessary second function I have to jump to and from. In this particulier case, the if/else if/else statement represents the exact logic, that's what makes this form so effective and straight forward, while the additional function method requires a bit of mental gymnastic to sort out

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

      And function calls are SLOW. You are very correct that second function is unnecessary. In fact, copying its contents back to the prior function is simple, adjust for person.age. That is the simplest and most readable IMO.
      Coding is all about readability to the developer and the maintainers to come. I use the rule "keep it very simple, the same constructs used repeatedly. Definitely NOT every construct the language offers using a different one each time." Find a simple one you can reliably work with and use the hell out of it. That gives the greatest reliability and best maintainability, as new developers on the project (or you in 6 months when you've fully forgotten what you did there) don't have to learn and make allowances many and apply different thinking to each.
      I use the rule "keep it so simple I can understand and work with it when I have a full blown head cold or flu and should be home in bed". Because that's the day you'll have to fix it, expand it, rewrite it. Or someone else will.

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

      There is a difference between readability and something just being what you personally are used to seeing. Something familiar isn't objectively more readable, even though you can easily read it.
      When someone says, "This is more readable IMO", they're using the word "readable" wrong. Readability that is opinioned is just familiarity.

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

      Not exactly. Sore, in this context it seems unnecessary: all four cases log a string, why would we have three of them in one code piece and others in the other? There is a reason, although in this case I think Kyle chose a poor example. It does make sense to have a separate validation function for a separate valid business logic concept. Is age valid for drinking is a matter of domain logic. Is the person object, if valid, of drinking age, may be a subject of some, say, individual controller which is not sure which input it got.
      The problem with this idea though is that the function returns a string which does not seem to make sense within it. But that could be just a poor example on Kyle part.
      I think the idea he presents is quite valid, just the example he uses is not the best, and he may've mixed up different ideas here thinking it was one:
      - using guard clauses improves readability (mostly, yes)
      - single return per function decreases readability (often yes with a notable exception of non-interactive debugging like through logging)
      - separating domain logic from data validation is a good idea (yes for more complex cases)

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

      That because you and most of this comment section are terrible coders

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

      yeah, like the first function IS the simplified function. He could've had the sole function use the exact same return functionality he used later, and just use `console.log(CanDrinkBetter(p))` for the initialisation.

  • @TheLukedb
    @TheLukedb Před 3 lety +2290

    If you avoid else because it's "confusing" it's not the syntax that's the problem

    • @moczikgabor
      @moczikgabor Před 3 lety +96

      Yeah, the example code is pretty much nice as is, and readable. However, in today's development flow I like the canDrinkResponse pattern better, as that function is reusable, the caller deals with the result, not hardcoded in function.
      With one exception:
      IF it's operation depends on the age method, then the not null check should be in that function, and it should return null on null input. Then it is self contained and not fail on faulty input.
      By the way these return statements are not bad. May not help readability either, but sometimes an if/else is more descriptive, sometimes returns. Usually for guard conditions, error checking, returning early is the most wanted, while determining some state from variables the nested if/else make much more sense.
      Transforming either one to another is a hack in my opinion. Back in the days in assembly jumping out of a loop were a norm. No other way. Then when high level languages came, everyone yelled that NO JUMPING OUT of loops, and all sorts of these design antipatterns which doesn't followed the block nesting logic of the language.
      It is pretty much a pain in the ass to exit from the middle of block in a nested loop, which is iside of a something when an error occurs. Return or goto is the only nice choice (which considered evil), otherwise you have to make an error flag and propagate out the error, which is ugly as hell, hard to understand, but not antipattern.
      Today, few decades later, it is acceptable again, even considered more readable to return from a loop. Mindblowing!
      My final words, agreeing with Luke: if a code is not a deliberate hack, but written in a logical way, nested blocks where feels appropriate, returns from loops where feels the easiest way, then it is a good code. Most likely, if it is easy to write, then it should be easy to read. If someone can't understand it, then either get better someone, or have him spend more time on understanding.
      We should not dumb down our thoughts for everyone to unrderstand.

    • @sehbanomer8151
      @sehbanomer8151 Před 3 lety +58

      I think the problem is nesting of if elses

    • @moczikgabor
      @moczikgabor Před 3 lety +53

      @@sehbanomer8151 Why would that be a problem? Nesting is a power tool of a language, any decent developer should understand few levels of nesting. If the conditional flow describes pretty much the same as a human would be doing then is it a most understandable and readable way. One can hack it more clever, it might run faster, but surely won't be readable.
      Sometimes it is necessary, for example there are embedded devices, but usually not needed even there.

    • @Hexolero
      @Hexolero Před 3 lety +50

      @@moczikgabor It isn't about the case where your nesting lasts for 6 lines and is totally isolated that is the problem, but cases where the nesting is 3 levels deep, 50 lines long, and is included in / includes looping, etc. In cases like this, a single level of nesting can cause the code to have exponentially more branches, which makes debugging harder, comprehension harder, and maintainability goes down.
      I would consider this "no else" idea a tool. Like any tool, there are times when it is useful and times when it is not. A good programmer will know when it will make the code more maintainable to reduce nesting to reduce branch complexity and when trying to do so would just make the code less readable.
      I think it is also instructive in that, here we see that the naive approach is to have a single function with a lot of conditional behaviour, and by following this "no else" mantra we arrive at code which is significantly smaller and has resulted in two functions, each of which achieve only one task. This is a typical ideal of programming, that each function should only do one thing. So I think that even if this "no else" approach is not always the right tool, at least in this instance it has led us to more idealistic code in a meaningful sense by trying to adhere to it.

    • @moczikgabor
      @moczikgabor Před 3 lety +24

      @@Hexolero I partially agreee and partially not.
      I disagree in that regard, that the main problem in an 50 line function is the excessive elses. Probably not, rather than organizational issue, which should be sorted first, and maybe eventually not the elses have to be blamed. And in the original case probably one can't even return at every else as probably other independent functionality follows, which might independent from the preceding condition.
      I agreee in that this is a tool, and a good programmer can (should) choose which approach is good in which case. The problem is that good programmers are not born from nothing, among other education materials, these sort of videos that SHOULD educate programmers to be good, thoughtful and open minded. This kind of teaching like "don't ever use this, always this", without options, without exaples of when it is apropriate and when not, which leads to short-minded thinking and mood-like aproaches of otherwise scientific things.
      The video is not bad, just biased. While I like the responsibility separation in the video's example, the canDrinkResponse function is still not independent in the video (I consider this as a bug), because the if null check is removed from it. It is to excessively shorten the code, but logically belongs there, and nobody going to have problem interpreting an 5 line function. While it is separated to two functions, it really the canDrinkResponse IS the business function, the other is just a console.log wrapper in this case.
      On a side note, in my opinion, separating an evil 20 line code to 5 function calls not necessarily makes it more readable, but most likely will make it run slower. Function calls have some cost over inline code, and excessive use is aa wrong as writing the whole code without functions. It is annoying that you have to open 10 files to understand what's going on, just to find out that all of them contains five 3 line functions which some way interleaved in each other. This is anything but readable. It is like buying books in 5 page packs. A good programmer should have enough brain to comprehend a healty sized file and a screen long function, if that's what required to solve the task.

  • @SuboptimalEng
    @SuboptimalEng Před 3 lety +682

    Exit early or "else" 😉

    • @differdf
      @differdf Před 3 lety +7

      Exactly - this is the same, just written differently. You still have to read all previous conditions when adding new one later in the code. Doesn't really solve anything. One good advice from this video is to use additional function to handle some cases. But still... this naming... it suggests boolean not THAT...

    • @uiopuiop3472
      @uiopuiop3472 Před 3 lety

      imma hit you with tha gunny
      sunny

    • @TalesMarinho
      @TalesMarinho Před 3 lety

      Yeah, the se isn't the problem. The problem is not has good design decisions

    • @cristianjuarez1086
      @cristianjuarez1086 Před 3 lety

      Meh it doesn't make sense, what if you cant exit early because you need to execute some parts outside the if? Idk about js, it is very necessary in c# at least

    • @uiopuiop3472
      @uiopuiop3472 Před 3 lety

      @@cristianjuarez1086 donot come cryin to me about your issus.
      i use tweny thosand dollar bills as my tissues

  • @CodingTutorialsAreGo
    @CodingTutorialsAreGo Před 2 lety +76

    Seems to me, the 'else's were the least of the problems in your code. It was the functional decomposition and the switch from '!= null' to '== null' that caused the real improvement.

    • @Rai2M
      @Rai2M Před 8 měsíci +6

      Prechecks are great. But the rest... O_O

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

      I was sitting here sweating when all of those console.log calls still existed halfway through the video. Thankfully he dediced to create a string function rather than a void function for the actual logic towards the end

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

      @@holonaut tbf the usage there was mostly just for demonstrative purposes. yeah, could easily have been heavily simplified with only 1 console log, but, generally, when you do need to print that much stuff to console, it's probably mostly for debugging and you're going to remove them anyway :D

  • @derekseverin3240
    @derekseverin3240 Před 2 lety +326

    Personally I think replacing 'if/else' with 'if return/if return', hurts readability more.
    You still have to check earlier in the code if every previous 'if' block has a 'return', in case the next block will not be executed. With 'if/else' you know straightaway that it's one or the other, not maybe this one if the previous one(s) didn't exit.
    In some cases it might help (it's more about the logic), but it is definitely not a 'good rule'.

    • @andrefig822
      @andrefig822 Před rokem +21

      the main problem with his initial code was the nested If/Else, not use of Else. The nested and deeply nested If/Else in a single method is what hurt readability and maintainability than everything else

    • @BasicMike
      @BasicMike Před rokem +2

      I think that with the push to using functional programming that this style works better than if-else blocks. As Kyle proves in this video, there's less code to work with, and therefore less possibility of mistakes. If we can truly get away from relying on variables to control inter-code responses than whatever we write will be more reliable. Avoiding the 'else' statement takes us a little closer to that goal.

    • @emissarygw2264
      @emissarygw2264 Před rokem +3

      Agreed.. Early exit/fast fail is a no brainer, and factoring in general is great. But I'm really skeptical that converting the range mapping into a series of guard clauses creates any meaningful improvement in readability or reliability. If/else chaining is a well established pattern for this sort of thing and our brains are wired to quickly comprehend things we've seen before. As another CZcamsr said - what's better than ideal? Standardized.

    • @SirZyPA
      @SirZyPA Před rokem +4

      @@emissarygw2264 yea, if i had to work with kyle and he did that, id get out immediately, because whilst it might work for him, using the traditional style that literally everyone else uses is better, since everyone understands it immediately, and doesnt have to worry about the code being exited too early.
      Not only that, he is spreading small amounts of code into functions, which means to read his code, youre gonna have to start at the top, then jump to the next function and so on and so forth, instead of just reading it as it is.
      When trying to get a job, it doesnt matter how much better you think your method is, if everyone else doesnt like it, you aint getting that job.
      I made some examples using a condensed version of his thing (just using guard clauses without the bulky functions), and then how you could do the same thing using the if / else method, with the code being shorter, and still on one line.
      // using guard clauses
      const a = { age: 17 };
      function canDrink(person) {
      if (person?.age == null) return console.log('You are not a person');
      if (person.age >= 21) return console.log('Yes 🍻');
      if (person.age >= 18) return console.log('Not in the US 😦');
      return console.log('Nope 👶');
      }
      canDrink(a);
      // What i would use
      const b = { age: 17 };
      function canDrinkBetter(person) {
      if (person?.age == null) console.log('You are not a person');
      else if (person.age >= 21) console.log('Yes 🍻');
      else if (person.age >= 18) console.log('Not in the US 😦');
      else console.log('Nope 👶');
      }
      canDrinkBetter(b);

    • @NickCombs
      @NickCombs Před rokem +3

      I'd say it does improve things. You're converting the negative conditions to positive ones, which is innately easier to think about. You're also pulling nested conditionals into descriptively named functions to help compartmentalize the thought process.

  • @xGshikamaru
    @xGshikamaru Před 2 lety +557

    Over the years I've found "clean code" is very subjective because a lot of people have differing opinions about what they consider clean. However a sensible rule of thumb is to avoid a function having too many branches. At some point it stops being readable if you have to scroll to see what the function does, but having too deep of a stack trace isn't a good thing either if you can't even name them apart.

    • @DeGuerre
      @DeGuerre Před 2 lety +21

      You should definitely avoid a function having too many branches. You should also avoid having too many functions whose only reason for existing is implementation detail. You should also avoid having a piece of self-contained logic being split into too many different locations (e.g. functions, classes, files, or whatever).
      Too many of anything is to be avoided. That is what "too many" means.

    • @pierretonnelier9994
      @pierretonnelier9994 Před 2 lety +8

      I "clean code" perl… and trust me, if you don't speak Perl, you don't read my work. "clean code" does not exist. Python was made for "clean code" and $°°° but it's a bloody nightmare to read… And If you work with binary cond else is half the work.

    • @xGshikamaru
      @xGshikamaru Před 2 lety +1

      @@pierretonnelier9994 I was a perl enthusiast too, one of my favorite algorithm involved a recursive function. It was compact and very clean in my opinion, but the thing is people around me just had a hard time wrapping their head around it, anytime I would write code in a functional way it was hard for them too and you could see by the way they wrote code that they just had an easier time with imperative procedural style. The lesson I learned from that was that you don't write code for yourself and sometimes something less compact with just simple logic is better. Language is just syntax, that's not really the most important thing, even though sometimes they canake things rather unpredictable (looking at you, JavaScript...)

    • @davidc1179
      @davidc1179 Před 2 lety +3

      @@pierretonnelier9994 I don't see why \t\t\t you think python code is a bloody nightmare.

    • @nickjunes
      @nickjunes Před 2 lety +3

      Yeah abstracting the body of a function when all you've done so far is write a guard clause is way to premature.

  • @johanullen
    @johanullen Před 3 lety +97

    After spending the better part of an hour composing this comment I'm hesitant to press the button. On the one hand, I don't want to come off as overly critical of a young developer. On the other hand here is a video with over 200k views, on a channel with over half a million subscribers, who gives some, what I argue is, bad advice.
    While parts of the have sound advice I think you are shooting yourself in the foot long term, in particular when it comes to returning early. I completely agree with how you should restructure the code with a blocker so that you don't nest your blocks, but the rest is basically not good advice.
    The first problem, as mentioned, is returning early. By returning early you have code with multiple places to change when you only want to change one thing, e.g. you may want to change what you return. It may look harmless when shown in an example as small as this but can cause havoc in a large code-base. It is a particularly big problem with untyped languages like JS because you don't have a compiler to help you find a, for example, type problem.
    The second problem is listing if statements without else if. You already showed that

    • @godDIEmanLIVE
      @godDIEmanLIVE Před 2 lety +3

      Setting a default value before knowing what you need is a performance hit for no reason.

    • @danlandia4399
      @danlandia4399 Před 2 lety +3

      @@godDIEmanLIVE Worry about having maintainable code before worrying about optimization. Outside of old school graphics coding or HPC very little of your code needs optimization more than it needs to be usable (and re-usable) for the long term.
      Once you find a bottleneck then you can work on optimizing it. But as my algorithms prof. said, the coding needing optimization probably wont be the section of code you thought it would be.
      And these days the compiler/runtime is better at optimizing your code than you are, so ensure your logic if formatted the same way the optimizer is expecting *cough*OraclePL/SQL*cough*
      Edit: Now I'm not saying "do not optimize", apply standard optimizations, don't walk a sorted array looking for a value when a binary sort approach would work better. Don't implement what should be a batch processing job as an OLTP process. Follow common sense. But that is part of writing code that makes sense.

    • @godDIEmanLIVE
      @godDIEmanLIVE Před 2 lety +5

      @@danlandia4399 My problem with this attitude as such is that this is the reason we have shitty and slow software. You just get used to premature pessimization for little reason and think that's normal and okay to do, because it makes your code "more readable" by 2% or what. Fundamentally, our job is not to write software that pleases us or is easy to read or follows some ridiculous paradigm for no technical reason. Those are secondary concerns. First order of business is to write fast and efficient software.
      The default thinking should be "how do I write fast and efficient software", not "what can I get away with, because it doesn't matter". Performance ALWAYS matters. Then and if there is a substantial reason to write some a bit less efficient code, it might be okay to write something more visually pleasing or lazy etc.
      Otherwise we're just not doing our jobs and we're making a joke out of software engineering. What other profession is as careless with their craft?
      Imagine designing a combustion engine and trying to convince your boss, that the pessimization of 10% in terms of power efficiency is okay, because it was too hard to design something more efficient or building it like that makes it look pretty.
      And there is plenty of software out there that is 100s of times slower than it should technically be. At that point, we truly are a joke profession.
      Long rant and I don't really disagree with some of your sentiments, but I am of the conviction, that what I wrote above should be the default way of thinking about what we do, so we can be proud of our craftsmanship. If then we say, okay here it literally doesn't matter what we write, because it doesn't affect anything really or just pessimizes performance by a tiny bit and it has other significant advantages to do it this or that way. Okay, nothing against that.
      P.S the thing about the compiler is very dangerous and most of the time it's wrong imo. Often bad performance is a problem of data locality and memory and cache access. You can easily pessimize your performance by fragmenting your data by a factor of 100s and your compiler can do zero to help you there. Same with choosing correct algorithms for the task at hand etc. etc. That is 100% your job.

    • @cm3462
      @cm3462 Před rokem

      I'm brand new, and thanks for posting this.

  • @barongerhardt
    @barongerhardt Před rokem +9

    For maintainable code, I would recommend throwing in the guard clause for things like invalid objects.
    Instead of separating into two functions just return the string and do the printing in the main. Other than debug messages, I prefer only the main loop to do any IO.
    function canDrink(person) {
    if (person?.age == NULL) throw 'Age is required member of person.'
    if (person.age < 18) return 'Nope!'
    if (person.age < 21) return 'Not in the US!'
    return 'Yes!'
    }
    const patron = {
    age: 29,
    }
    const drinkingToday = canDrink(patron)
    console.log(drinkingToday)

  • @ashlandwithouttheshd
    @ashlandwithouttheshd Před 2 lety +10

    Ladies and gentlemen the result of hiding the dislike count

  • @dansadler
    @dansadler Před 3 lety +278

    With one exception: do not turn the code into a maze of returns, keep them as close to the beginning of the function as possible, or at least make them visible inside your code.

    • @flowerofash4439
      @flowerofash4439 Před rokem +2

      it become a maze if it only have one return, just like a maze in general it only have one exit.
      if you have early returns you don't have to read all of the code just to understand one path of the logic.
      one early return in line 3 will reduce the mental burden of reading line 4 to line 10, because you know that one path of logic already ends in line 3 and is not going to be touched in line 4 to line whatever because of return statement in line 3.

  • @dominiklukacs7677
    @dominiklukacs7677 Před 2 lety +880

    I don't think avoiding else completely is a good idea. It can help your function if you use early returns to get rid of edge cases, but if you have a more complex check, or you are doing calculations instead of just returning on each leaf of the binary tree then this method will probably not work. Also you shouldn't really turn one working function into several just for the aesthetics, it's not going to make it more readable if you constantly have to jump between 3-4 functions that call each other. In some cases it can work, but you shouldn't take either of these as general rules, more like neat tricks you can do in specific cases

    • @tommj4365
      @tommj4365 Před 2 lety +2

      Yea but in the end he says this is more of an exercise to help you and else statements may still be a better option

    • @TheXLAXLimpLungs
      @TheXLAXLimpLungs Před 2 lety +3

      if you use an else for a return for edge case you can just flip the if check to be inverted and achieve the same thing. if it's a specific else if, that's different, but still there are ways around it that use less code but maybe is less straightforward to read.

    • @cooperfeld
      @cooperfeld Před 2 lety +3

      Just wanna add that if/else (branching) can be converted to binary logic and caching the results into booleans (howto-details on request). Timely I prefer this, aware it's merely another way of writing if/else. I use it for readability, and for reducing code path complexity in larger projects, which can be beneficial for testing and debugging (referring to code quality metrics). Else-If cascades I completely avoid. For conditional value assignment, I favor the ternary operator where possible (sign = value < 0 ? -1 : 1). Sometimes I use if/else for code flow control, while preferring the alternative: if (condition == true) call A, if (condition == false) call B. I know it looks a bit odd).

    • @KlebinDaBoca
      @KlebinDaBoca Před 2 lety +17

      Not using else on usual day-to-day tasks: a good exercise to help you understand and actually improve your flow control skills as a developer.
      Not using else when actually needed just because someone said it's better: stupidity.
      The else keyword do not exist to endorse lazy development though. It has a purpose and it can and should be used as long as it fits that purpose.

    • @PianoMastR64
      @PianoMastR64 Před 2 lety +9

      I generally only abstract code into functions if I will or think I will use it more than once

  • @TheIlidius
    @TheIlidius Před 2 lety +12

    Using guard statements is a valid way to make you code less cumbersome to read because you removed one depth of nesting, that's a really good takeaway. Removing anything *else* form that code doesn't really give anything, in this case it's better to just stick to whatever convention you have in your codebase already and stick to that.

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

      Agreed if you are working in an existing code base. Making new form changes can really become a burden later. In this case where an else clause can be reduced to a single line, these are improvements, so long as the second function's code is put back into the first--the second function is unnecessary and SLOW.
      I've 40 years programming experience, really learned the single return point from Pascal programming in 1980. I didn't like multiple returns from functions especially long ones or complex ones. Before syntax colored editors finding where the code actually exited was a pain.
      The trouble with multiple subs breaking down the functioning is that they become scattered in large files, chewing up time finding them, and across multiple modules, such as when refactoring or expanding the calling parameters and adding new associated logic. There is also a large performance hit to calling a subroutine. So the rule there is "keep your code simple, use functions to encompass a reasonably strong amount of code, generally not just a few lines, and so minimize the number of functions needed. And keep them close together as best you can. Seeing them all together is usually necessary when extending their functionality or refactoring."

  • @craigsparton
    @craigsparton Před 2 lety +16

    I do prefer guard clauses. When used to eliminate nesting levels on large if statements I think they increases readability in most cases. But I also think every situation should be evaluated on its own, rather than just arbitrarily restructuring every program to remove else. There are many usage cases where using else is cleaner and more efficient, particularly when there is more code that follows and you can't just return.

  • @cool-dev
    @cool-dev Před 2 lety +853

    I just realized how many CZcams videos teach “bad” practices with confidence. Maybe I should start doing this to make some money

    • @RoastLambShanks
      @RoastLambShanks Před 2 lety +26

      are you saying this technique is bad, or are you saying other videos are bad? If so, why?

    • @tetraedri_1834
      @tetraedri_1834 Před 2 lety +36

      But hey, there are 25k likes, this cannot be anything else than 100% legit!

    • @sehrgut42
      @sehrgut42 Před 2 lety +53

      Right? This dude should be ashamed to think people are WATCHING this. I thought it was an April Fool's joke at first...

    • @sajeucettefoistunevaspasme
      @sajeucettefoistunevaspasme Před 2 lety +4

      you have to teach about the else statement
      yes could be optimized but hey shouldn't scare newbies with advanced technics

    • @scmsean
      @scmsean Před 2 lety +37

      @@RoastLambShanks 1, you shouldn't make a function expecting the function calling it to have already done a null check. A switch statement would been the best way to do this.

  • @omeryehezkely3096
    @omeryehezkely3096 Před 2 lety +356

    I never had a problem reading code due to usage of "else". On the other hand I did encounter difficulties due to early returns and unneeded nested function calls which simply break the locality of logic.
    I'm not in favor of spaghetti code. Just use commonsense when writing code and remember that there is nothing inherently wrong with "else". Don't waste your efforts as an anti "else" fanatic.

    • @unknownalien3837
      @unknownalien3837 Před 2 lety +21

      This. Different situations, and thus different requirements, require different implementations and different solutions. This video is superfluous and completely unnecessary. I would argue it would lead to more messy code following this videos advice. The concept he's loosely touching on is actually short-circuiting, which is a beneficial technique for improving algorithm efficiency. "Guard clause", in my opinion, is a terrible name for a short circuiting if

    • @jeffspaulding9834
      @jeffspaulding9834 Před 2 lety +2

      I've had issues due to overuse of else, but only in programming languages that offered no viable alternative. When if/then/else is your only flow control, anything slightly complex becomes a nightmare.
      Normally I'd just advise avoiding such languages, but sadly it's not unusual when dealing with industrial control software (looking at you, Wonderware) that BASIC dialects are still the norm. Supposedly, they're easier for someone unfamiliar with programming to debug, but honestly if you have someone unfamiliar with programming tinkering around with heavy machinery controls, you should be sued into oblivion. This stuff can kill people.

    • @Disatiere
      @Disatiere Před 2 lety +6

      The main issue with this video is that ... JS supports switches which in this case wouldve been the correct thing to use to simplify it not just visually but also in code so it only has to be evaluated once.

    • @playmusic8056
      @playmusic8056 Před 2 lety +4

      @@unknownalien3837 yeah, "guard clause" is a fine name for a clause that guards against invalid input. But this guy also uses the term incorrectly for simple short circuit returns that are not really guarding against any unexpected/invalid input.

    • @HerbaMachina
      @HerbaMachina Před 2 lety

      @@Disatiere JS does not support switch statements.

  • @cybernit3
    @cybernit3 Před rokem +9

    Years ago in C, if there is a lot of if/else then I would use the SWITCH statement, I found that helped make it clearer. Thanks for the reminder and advice to avoid using a lot of if/else in code.

    • @irrelevant_noob
      @irrelevant_noob Před rokem +5

      Except switch doesn't work with comparisons, it needs discrete values as labels. :-B

  • @guffels
    @guffels Před 2 lety +8

    One could argue that adding an extra function to replace if statements also unnecessarily complicates code. I find reading the code without the else requires understanding the run-time order jumping between functions versus being able to parse the logic manually.

  • @SRISWA007
    @SRISWA007 Před 3 lety +324

    Whenever you're working with a single variable, try and use a switch statement instead. Something like this:
    ```
    switch (true) {
    case age < 18: return "Nope";
    case age < 21: return "Not in the US";
    default: return "Yes";
    }
    ```
    The beautiful thing about a switch statement is that, you can add one more condition, pretty easily without changing much.

    • @Nunzio.o
      @Nunzio.o Před 3 lety +4

      Default still works like an else this not solves the problem. The point is that whatever you wanna use for if a decision has to be taken or not you dont wanna be in the condition that else or default accepts unexpected results like null or undefined so you need a guard as explained in the video! Have a good day ;)

    • @SRISWA007
      @SRISWA007 Před 3 lety +21

      @@Nunzio.o I get your point. But you can always have an if statement for checking whether the variable is `undefined || null` before getting into the switch.
      OR, better yet, you can literally have an `if` statement inside the `default` case.
      What I showed was just an example of how to use a `switch-case` statement for single variable conditions, rather than an `if-else` ladder.
      Hence, that's the beauty of a `switch-case` 🙂

    • @colinhoward2200
      @colinhoward2200 Před 3 lety +17

      Multiple returns in code are a really bad idea. It is why they are excluded for safety critical system in MISRA and IEC 61508 (Functional Safety Standards). These standards have grown as essentially a list of lessons learned from a variety of safety critical development projects over decades.

    • @colinhoward2200
      @colinhoward2200 Před 3 lety +17

      You could still do this :
      let result = ""
      switch (true) {
      case age < 18: result = "Nope";
      case age < 21: result = "Not in the US";
      default: result "Yes";
      }
      return result;
      This solves the non-multiple return issue

    • @CallousCoder
      @CallousCoder Před 3 lety +7

      switch statements are UGLY imo. You introduce more nested brackets which doesn't improve the readability.
      In that is the case, make a static list or hash with a function pointer! That's more clean.

  • @perlohmann
    @perlohmann Před 3 lety +358

    I would be vary about this “no else” approach. You are introducing implicit conditional structure into your code and while it might make sense if like in this case it is one liners, then I have seen plenty of cases where if statements are long and not knowing the if statements must come in that order is just bugs waiting to happen.
    Guard cases on the other hand are great!

    • @YtiaEray
      @YtiaEray Před 3 lety +10

      This! I would go one step further and adjust the if statements so the order doesn't matter at all. Yes this adds overhead but it will make sure that somebody who messes with your code will not run into issues without fully understanding what that code does.

    • @yevhenkozlov286
      @yevhenkozlov286 Před 3 lety +5

      well, with "else" ordering is also critical. The only way to ensure ordering does not matter is to expand every single condition, like "if (person.age < 21)" into "if (person.age < 21 && person.age >= 18)". But that's bad to maintainability too, do you agree?

    • @YtiaEray
      @YtiaEray Před 3 lety +9

      @@yevhenkozlov286 Absolutely! The ordering matters in an "if", "elseif", "else" block too - But on refactoring I would tend to keep the order there more likely compared to a bunch of single if-statements. By design in such a block only one branch will be executed - I dont need to worry about the content of the branch itself. As perlohmann mentioned above its quite easy to read if its one liners.

    • @BrandonSalazar1257
      @BrandonSalazar1257 Před 3 lety +13

      Yeah, this looks like a lot of bugs waiting to happen, for whenever the people edit your code. Not a big fan of this

    • @kaspalone
      @kaspalone Před 3 lety

      Exactly my thoughts. Besides, it applies pretty good on JS Web Programming. On System Porgramming or other areas, I dont think it's a good idea, beyond the Guard cases.

  • @Zanador
    @Zanador Před 2 lety +25

    Guard clauses are useful for stuff like the initial "not null" check, but I'm not sure I agree with the other changes as much. Moving stuff that's only used in one place into a separate function IMO makes code harder to follow because you need to move around to multiple different functions just to follow what's happening. With more complex functionality you might end up bouncing between like 4 or 5 different functions just to follow the logic of one operation, and in all that bouncing around it's easy to lose track of what exactly is happening, when, and why.
    As for the early return clauses with every "if" statement, I don't really see how it's any easier to follow than just using "else". In fact it increases the chance that someone new to the code misunderstands it because they miss the return line and don't realize that only one "if" is going to be used. If you really hate "else" then it makes more sense to just use a switch statement; in fact all you're really doing by returning after each condition is jury-rigging your own switch statement out of ifs.

    • @FireSiku
      @FireSiku Před rokem +3

      Yeah, breaking the code into several function just to avoid a straightforward If/else statement is what leads to "enterprise code" such as splitting FizzBuzz into a FizzResponseStringFactory and a BuzzResponseStringFactory, both being children of a StringFactoryFactory of course. (I know its one hell of a slippery slope and mostly for comedy)

  • @cuuy
    @cuuy Před rokem +8

    I've often omit "else" after "return" myself, for example when I write recursion and start with the base case. Mainly because I'm lazy. But I disagree that it's generally more readable, and especiallly that it produces less mental overhead. To wholly understand what the function does, you pretty much have to add the missing "else"s to reconstruct the control flow. It's easy for experienced programmers, but it rather adds a bit more to the mental overhead than makes it less. And I don't think "canDrinkResponse" is a good example for extracting a function. I don't really see any advantage doing it except omitting that one "else". So it comes down to one level of else-nesting vs. an extra function. I'd say that one level of else-nesting produces less mental overhead.

  • @Bjoernqqq
    @Bjoernqqq Před 3 lety +166

    Using console.log is in my opinion a special case that’s not really useful outside of demonstrations.
    I would have changed the function so that instead of canDrink (which btw sounds like it returns a Boolean), I would’ve named the function something like getDrinkingMessage and have it return the string. This way, you would not have to have an additional function and in your main program flow, you would console.log the result from that function instead. And because you return the string instead of using it inside the function, you also improve the reusability of your code.

    • @Greghouse
      @Greghouse Před 3 lety +1

      +1 That's what I thought too!

    • @MartinOmander
      @MartinOmander Před 3 lety

      Good point, that would improve reusability, and testability too.

    • @gizel4376
      @gizel4376 Před 2 lety

      isn't it what he did in the last exemple ?, btw i don't know javascript, but i guess Function mean you can return what you want?
      for the name, i totally agree he should either find a different name or add something like CanDrinkStrg

    • @venominjected
      @venominjected Před 2 lety +3

      It should be common knowledge that functions beginning with "can" or "is" *should* return a boolean. Such rules make code easier to read, especially in untyped languages like JavaScript.

    • @spl420
      @spl420 Před 2 lety

      @@gizel4376 no. He just split function in two for nothing, he could just replace all ifs with function, that he extracted and console.log(canDrink()) outside of function

  • @corryunedited8154
    @corryunedited8154 Před 3 lety +640

    Maybe I'm actually missing something, but this seems like a lot of work that could be simplified by just using a switch statement.

    • @ryanswatson
      @ryanswatson Před 3 lety +101

      I literally can't believe I watched this through. No wonder there are so many comments on this video, i'm not going to re-invent the wheel for a single value checker when we have the switch statement... it will in fact make it even more complicated to read. At least when you see a switch, you can immediately see the intent.

    • @JurajOravecSGOrava
      @JurajOravecSGOrava Před 3 lety +81

      @@ryanswatson nah, switch can check for exact vaues but it cannot check if something is greater or smaller than that value (well, it might depends on actual language used)

    • @Whimfoome
      @Whimfoome Před 3 lety +8

      The Rust compiler turns if .. else statement into a match (switch) anyway.

    • @williambrasky3891
      @williambrasky3891 Před 3 lety +14

      @@Whimfoome most compilers do. It cuts down on number of ops executed on the metal.

    • @graysonofthewood3747
      @graysonofthewood3747 Před 3 lety +17

      Corry, I agree if the language is not JavaScript. In JavaScript, I’ve seen many people avoid switches because they are implemented to automatically continue from one case clause to the next and must be manually stopped with the “break” keyword. In general, not a huge problem but you always have to remember to break, which is just one more thing to worry about. As such most people would only use switch in JavaScript when returning a value because that automatically breaks out of the switch without running the results of the following case clause.
      That would not work in his example because JS switches only check equality, not greater than or less than. Now if we were working in something like Elixir, we could use “cond do” and call it a day :D

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

    I appreciate that this is 2 years old and you may have already covered it in a future video. My favourite technique for dealing with your problem is using the try/catch coding style. It works similar that you switch your checks around.

  • @BasicMike
    @BasicMike Před rokem +1

    When I was programming in ANSI-C we used to call this 'utility programming' because you simply use a utility program or subroutine to handle low-level functionality. It took a lot more planning, mostly with bubble charts or track diagram models, to determine when a utility routine was needed, versus just embedding the functionality in your main program. The end result was worth the extra head banging. Aside from syntax errors that were mostly typos, this worked faster and with fewer flaws than just banging out code any possible way you could.

  • @searous5590
    @searous5590 Před 3 lety +330

    Just learned guard clauses have a name. I'm 100% self taught and I started doing it on my own because it felt right.

    • @travcurt
      @travcurt Před 3 lety +7

      Same!

    • @jp0678
      @jp0678 Před 3 lety +4

      Same!
      Only in my case, I thought it's unnecessary nesting. If it's not that long though, I just use multiple ternaries in one line.

    • @StaglyMusic
      @StaglyMusic Před 3 lety +1

      good luck to all of you guys! :)

    • @davidheizer6232
      @davidheizer6232 Před 3 lety +4

      I agree with this. I did not know what a guard clause... I think these are also called validators

    • @DoctorAndy46
      @DoctorAndy46 Před 3 lety

      Hey hey, same! And then when two functions in two separate files need to use the same smaller function, you can move it to a global 'utility' file. I discovered that you can return not just strings, but also the whole fetch, so you can append to your own functions. That just blew my mind 🤯

  • @FoxywithaRubikscube
    @FoxywithaRubikscube Před 3 lety +243

    Sees "why I don't use else when programming" Me: WTF
    Sees "web dev" Me: ahhh makes sense

    • @nov366
      @nov366 Před 3 lety +5

      Omg I imagine assembly of such code in c

    • @giladshmueli5831
      @giladshmueli5831 Před 3 lety +17

      @@nov366 it's not impossible, but I personally don't fully agree with the "avoid else AT ALL COST" statement. It can be readable with "else" statements imo, but when coming to such deep nesting, if you really go deep down a rabbit hole then the idea is a good practice to avoid so much heavy indentation. (weird how rabbits have nests in this scenario)

    • @AntonNidhoggr
      @AntonNidhoggr Před 3 lety +15

      @@giladshmueli5831 imo avoiding anything at all cost is a bad practice because in most cases you're usually dealing with symptoms and not the problem. I mean overcomplicated code frequently is a result of a) not reusing your code properly b) not splitting functionality properly c) 'type as I go' attitude without any planning whatsoever. 'Else' is just a cherry on top of it.

    • @FoxywithaRubikscube
      @FoxywithaRubikscube Před 3 lety +5

      @@AntonNidhoggr precisely. If the keywords didn't have a good purpose, they probably wouldn't be in the language.

    • @jtwo6307
      @jtwo6307 Před 3 lety +2

      I'm on the same WTF group, lol

  • @hotflashfoto
    @hotflashfoto Před rokem

    Very good information. Cleaning things up to make it more readable is for the human, which means it'll be easier to manage going forward, whether for you or another person.
    I agree in part with the other comments about drastically reducing the number of ELSE statements. I rarely use them, and like @cod3r1337 mentions, I use SWITCH or CASE statements because they are easier to manage, plus I can add another branch with very little effort compared to IF/ELSE.
    There are even times when I'll use a single CASE and add a final one that collects all the remaining results by adding a comment "Blank by design" just so the next coder will realize I didn't forget something. (It's usually me having to look over my own code, so it serves as a reminder as well.)

  • @maximilian.volt0168
    @maximilian.volt0168 Před rokem +6

    In my opinion, "else" does not hurt a code's readability (unless, of course, long nested cases are being used). I think it makes the reading way more natural, especially for someone who is pretty new at coding. Also, removing it doesn't really improve it, it changes the way it appears better to you in terms of simplification, even though numerous functions for just one specific action do make the reading a little more complicated; because after all it's just 1 small process that makes the executor skip to the else's code block, so even if you removed it it wouldn't really change that many CPU processes and the code would be more clear to who's new at coding, as the "else" keyword is a fundamental ground to step on when coming to a code's reading naturality.

  • @NakamuraSatou
    @NakamuraSatou Před 2 lety +360

    I personally believe else increases readability by group items tougher.
    And for cases more than 4, you should use a switch statement anyway

    • @salakameli
      @salakameli Před 2 lety +5

      Yes, exactly what I think. But I think these videos provide good beginner tips, in general

    • @kirchann
      @kirchann Před 2 lety +8

      switch(true)

    • @Chailotl
      @Chailotl Před 2 lety +12

      The switch statement only works if you're checking specific values from only one variable.
      One situation where you could easily have several chained if else statements is when doing validation with clear error messaging

    • @Fandrir
      @Fandrir Před 2 lety +4

      Agree. Even in this case, i find it harder to see where the group of checking the age starts and ends with all the returns. With the if and a few else statements, it is way clearer to see what belongs together.

    • @rustyutb
      @rustyutb Před 2 lety

      i used to think just like you... but i'm reading "clean code", by R. Martin, and it seems that using nasty if/else statements, or either switch/case, you would be violating the open-close principle. After using this technique i could significantly increase the quality of my code, also making it more readable... check this video from Kyle and then tell me your impressions: czcams.com/video/-ptMtJAdj40/video.html

  • @fandigilidubis5184
    @fandigilidubis5184 Před 3 lety +240

    But when the logic gets more complicated you could end up with tons and tons of small functions which don't really improve code readability. I think the best option is not to avoid the else keyword but rather use common sense - if you feel like your code is getting harder to maintain, then refactor it. It's the same case as code optimization: think about it only when it starts to matter.

    • @tomg0
      @tomg0 Před 3 lety +12

      Yeah, this is only useful for use cases like the example shown when a function has a single primary purpose, not a function that is meant to tie a variety of other functions together into a workable program.

    • @Martin-pb7ts
      @Martin-pb7ts Před 3 lety +12

      @@tomg0 True, but if a function doesn't have a basic primary purpose then your function is doing too much.

    • @noahsmith2555
      @noahsmith2555 Před 3 lety +29

      @@Martin-pb7ts I would disagree. There are cases when breaking down a function into smaller functions provides no benefit, and putting the majority of the code in one function would be better. Functions are useful and necessary to help reduce duplication of code, but they are not necessary to group it into parts that can easily be distinguished. And then there’s the performance overhead of function calls, minimal, but it exists, and should not be neglected.

    • @dennisgatere7821
      @dennisgatere7821 Před 3 lety +7

      @@noahsmith2555 I would disagree based purely on what is the intention of many small functions. If it allows you to have a more descriptive set of tasks based purely on the function names and allows better unit testing then its worthwhile. Functions aren't just useful for reducing duplication but should be used if it helps with communicating your ideas to others using that codebase, I would personally always go for readability if that is the intention of many small functions that a developer has chosen

    • @blueble3997
      @blueble3997 Před 3 lety +16

      @@dennisgatere7821 I think youve missed the point of the argument, which was that using a lot of small functions wasnt outright bad, but in certain situations it is. Most of the time using small functions is good, however, there are some specific situations where you wouldnt want to for various reasons. Maybe theres also confusion around everyones definition of a "primary function". What is classified as a primary function? Thats a rather subjective term. There is a point at which increased abstraction comes at a cost in terms of readability, and of course, performance. Also, regarding your view on readability, while using many small functions can certainly help make your code more readable to others, theres no reason that the same cannot be done if few functions are used (Comments exist for a reason).

  • @bluetopia42
    @bluetopia42 Před rokem +15

    I absolutely agree with you when it comes to cases where you may have to many nested if/else-clauses that it gets unreadable. But readability is not all! If you use an ELSE, you exclude everything that is not covered by IF. This is means ultimatively, that you have to cover ANY case, that is not covered by your IF. It's just logically easier to use an ELSE instead of "IF'fing everything out"... you little hacker. ;) Very nice video.

  • @guilhermelopes7809
    @guilhermelopes7809 Před rokem

    I really like your videos, they go straight to the point and the explanations are very good. Thanks for your work :)

  • @jmitchell2464
    @jmitchell2464 Před 3 lety +226

    Developers should always be cautious of other developers telling them NOT to use aspects of a programming language. There are developers out there who say OOP is bad and that you should only use functional programming (OOP is good). if else is probably the first keywords in programming, macros are literally if else statements. All if else does is to determine what you give it, is true or false, if you have bugs that means you haven’t properly tested your code (and that’s ok. Don’t blame it on if else). And if your having trouble reading if else statements then your going to have problems reading code period. Like one commentor stated previously this is more of a style thing NOT a proper way of coding.

    • @SrIgort
      @SrIgort Před 3 lety +6

      True.... Unless you're doing things like
      if (x)
      If (y)
      console.log("x & y")
      else
      console.log("x")
      else
      console.log("y")
      .... Never do this.

    • @theonly5001
      @theonly5001 Před 3 lety

      @@SrIgort but you are bot checking for one thing. You're checking for multiple.
      There might be a
      If(x) then resultx = a
      Else resultx = A
      If(y) then resulty = b
      Else resulty = B
      Return (resultx & resulty)
      That is checking for two seperate thins. But still using the else keyword.
      And that is not what is happening here.

    • @CalvaTV
      @CalvaTV Před 3 lety +9

      Develpers should be cautious of developers who categorically say ”X is good”, as in meaning ”X is always good”. OOP has its uses, but there are many instances when you are much better of figuring out a functional solution to a problem. I can recommend this video which shows what is sometimes within reach if you consider the functional approach: czcams.com/video/vK1DazRK_a0/video.html

    • @jasontiscione1741
      @jasontiscione1741 Před 3 lety +8

      We're talking about JavaScript, a language originally designed for people who don't know what they're doing by people who didn't know what they were doing, some of whom even intended for it to fail and be replaced by VBScript.

    • @everyhandletaken
      @everyhandletaken Před 2 lety

      ^ this.

  • @feandil666
    @feandil666 Před 3 lety +177

    The problem with multiple return statements is that it's easy to forget some that are in the middle of a function and not realise some part of the code doesn't get executed when you modify the code later. it's a source of bugs that can be easily avoided, that's why they teach not to do it. Personally I do use early returns a lot in guard clauses exactly like you, defensive programming where you check your assumptions first is really good form. But past that I do avoid multiple return statement, caching the "result" in a variable is way more sensible, as you can add stuff later on to the end of the function, and you're sure it's gonna be reached in all cases.

    • @justinbordage4302
      @justinbordage4302 Před 3 lety +8

      Personally, I think that's just as prone to bugs, since you have to make sure you're not affecting the result between your "stop" point and the return. I'm not saying it will never be useful, but I do like the multiple return because it means I can safely ignore the rest of the function from the point of exit onwards without worrying about how I handle the variable later on.

    • @MartinOmander
      @MartinOmander Před 3 lety +6

      I hear you. But if you stick to Robert Martin's rules for function length, multiple return statements are easy to spot.
      "The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. Functions should not be X lines long."
      Different developers use different values of X. I find that keeping my functions under 20 lines makes them easier to understand and test.

    • @feandil666
      @feandil666 Před 3 lety +14

      ​@@MartinOmander I dislike these kind of rules, some functions are long because they do a linear process that logically belong together. cutting them in pieces just for an arbitrary length rule adds a lot of overhead and is extremely annoying to read through. plus it's slow to code, especially when you have to change parameters. that being said, I obviously avoid multi pages functions, but they end up being cut up according to my refactoring needs, not according to some arbitrary layout rule.

    • @MartinOmander
      @MartinOmander Před 3 lety +5

      @@feandil666 Agreed, how we organize our code should be driven by our refactoring needs, not some rule.
      Whenever I've written a function, I check its length. If it's over 20 lines, I take it as a signal to think about whether it should be split up. About 80% of the time, splitting it up makes the function easier to understand and test.
      Maybe this "rule" should instead be called a "reminder to think".

    • @ThePC007
      @ThePC007 Před 3 lety +2

      @@MartinOmander I've kinda been thinking about this. Say you've got a struct that holds some data as well as two functions, one for generating a string out of that data (for saving to disk, sending over a network, printing to console, etc.) and another one that parses such a string to get the original data. In my experience, the parsing function can become fairly large, especially if the structs holds large amounts of data. For every field you need to get the corresponding string token, return early if it is null, then optionally convert it into an integer or float, then perhaps return early if the data doesn't make sense (input sanitization can be kinda important), and then apply it to the struct. You can hardly shorten it, and you also cannot easily break that up into multiple functions either. Any thoughts about this?

  • @jl6723
    @jl6723 Před rokem

    I like the benefits of If-Return coding as it forces you to functionalize complexity, which is better than having giant singular functions.
    However, I do have a caveat, which is that you should still use else inside the main function block. This is because doing two state checking where different functions are called tends to be suitably readable still and the main reason we tried getting rid of else (to prevent additional blocking). Generally the rule I would say is try to only stay within the top two blocks for a function and if you need more blocks create a function.

  • @tomsterbg8130
    @tomsterbg8130 Před rokem +22

    I have NEVER heard that you must have only one return in a function and this shocked me. Returning at multiple places and branching off your functions is the best way to improve readability when you have these giant blocks.

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

      The problem with multiple returns is people don't always expect them. If someone puts in an unexpected return it can catch you out. If it's glaringly obvious that you're using multiple returns, I don't see a problem. Most decent programmers would document how the function works and explain that multiple returns are used and possibly even why that particular paradigm was used.

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

      ​@@thesupercoach The single-return notion comes from back in the C days where it actually had a good reason. The idea is that if every function has a single entry point (they do) and a single exit point and you allocated memory at the beginning of the function and freed it at the end of the function then you shouldn't have any memory leaks (this assumes that you weren't using "goto", which is there, but I've never seen anyone use it - maybe one person across 35 years).
      I agree with @thesupercoach that multiple returns can catch you off guard. It depends on what the function is doing. It's possible that by not having the single return you're leaving some other resource open because someone put in a return in the middle of the function and now, while not a memory leak, it could result in other bugs.
      With regards to the "never use an else". I don't agree with this. I do agree with: make your code readable/manageable/maintainable and if reducing elses / having a return helps with that, I'm not against it.
      One other thing I'll mention is that you need to consider debugging with this. It's a subtle difference but when you're walking through the code or "stepping out" of a function then a mid-function return may surprise you (meaning, you missed it while looking at the code and assumed the code was running all the way to the end of the function and are scratching your head as to why something happened when it doesn't make sense).
      I'm not a fan of the "this is the rule" and just living by it (like the single return). I think it's important to understand the history and why of it so you understand how implementing that rule (or not) could affect the program. So many people I meet just want to have the "rule" and then just implement it going forward without thinking about why/implications.

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

      Multiple return points means the person reading the code has to scroll to all of those random points to actually understand the output of a method.

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

      Well written function should have one type of return. And if it has only one type of return, there is no reason to use mutiple return statement in one function which leads to way better readsbility and resusability if the function. In the edge case the video showed, it should raise error.

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

      Well, if you actually had a degree in Computer Science, you would have heard about it... It is considered PROPER programming to only have a single exit point in a routine... Back when I was working on a contract for NASA at one of the major aerospace contractors, we came up with a method using the 'C' pre-processor (i.e. via various macro definitions) to add to the language so that it a new command "RETURN"... This macro was in fact hiding a "goto" that went to a label that was hidden under an "ON_EXIT { }" block which would do the actual "return"... This allowed you to create the ON_EXIT block to clean up any memory that had been allocated in the routine... One of the dangers of having multiple exit points in a routine is memory leaks... Another is opening files and not closing them... Code is either engineered or it is hacked... The author of this video obviously is the latter... :(

  • @bigmike-
    @bigmike- Před 3 lety +154

    I would advise *against* falling into JS-only development patterns (even when writing JS), as it makes it harder for multi-language developers to deal with your code.

    • @lajexander
      @lajexander Před 2 lety +8

      Yeah. I wanna see him try to do this for VHDL now.

    • @snesmocha
      @snesmocha Před 2 lety +8

      @Brandon Busby
      If you don’t want to read;
      Tl;dr, this is the only language that contains early returns and is super unstandardized which will fuck everyone over programming in this style
      let’s take this for example in c/c++, the current language I specialize in
      ```c
      if(d == "a")
      {
      printf("you printed the letter
      ");
      }
      printf("you didnt print the letter
      ");
      ```
      Both will execute, this concept does not work in c/c++
      Not to mention in a python style language where curly brackets are not used in, this is just painful to deal with.
      You should never stray from the standardized language systems that everyone is accustomed to. Everything in this video is bullshitting you and is just plainly lacking of basic common sense. It does not affect performance either so why bother with this? It’ll make your code horrible and not even readable.

    • @katie.daydream
      @katie.daydream Před 2 lety +26

      @@snesmocha Have you actually tried, or did you just assume you're correct cause you specialize? C and pretty much every C-like language allows early returns.
      This literally works in C:
      void someFunc (int a) {
      if (a < 0){
      printf("a < 0
      ");
      return;
      }
      printf("a >= 0
      ");
      }

    • @katie.daydream
      @katie.daydream Před 2 lety +2

      I suppose you might want to avoid early returns when dealing with malloc when it comes to C specifically, and so maybe you would want to make that a standard your C projects. But that's an issue specific to C, and so in many languages this is totally ok.

    • @azaria_phd
      @azaria_phd Před 2 lety +26

      Yeah, "return console.log()" is a fucking aberration. It hides the fact that console.log doesn't actually return anything, and that your intention is not even to return anything, just to save one line of code.
      Trying to turn everything into one liners by taking stupid short cuts like this will make your code a fucking nightmare to deal with

  • @maximtheconqueror
    @maximtheconqueror Před 3 lety +343

    it's a matter of the paradigm you are working with. The way you programmed is strongly align with functional programming, because you are centering yourself in within conditions (functional programming). And avoiding the need to keep track of a variable (state). That's why the code looks cleaner and more abstract. It's more cohesive. In the other hand using if/else and creating a variable (state) to then modify it. Makes more allusion to Object oriented programming. It's a matter of how you are centering yourself. I strongly prefer to encourage the way you code because functional programming makes allusion to recursion and it encourages people to create better abstractions. The answer to whatever you need to use If or else is mostly redundant. Both work, it's a matter of preference.

    • @MaulikParmar210
      @MaulikParmar210 Před 3 lety +16

      It works only when writer itself understands multiple paradigms and still be able to make choices depending on project standards. Unfortunately most programmers are unaware of it till significant amount of time until they realize this with other codebase, best practices and from their own experience.
      In my experience it's always about sticking to common tongue that other developer's speak when it's a teamwork and always a personal choice when going solo.
      At the end of the day all loops, conditions and switches are converted to jumps and jump with conditions in either real cpu or virtual machine, those who are fimilar with assembly can easily relate. This essentially abstracts english mnemonics that we use to write executable code.

    • @ade8890
      @ade8890 Před 3 lety +21

      I don't think guard clauses is a "functional vs OOP" situation. Guard clauses are just a generic way you can safe guard your arguments or safeguard the value of some variable/state according to some conditions. Which is equally applicable to both OOP and functional paradigms.
      But yeah, it's a matter of preference. Guard clauses are great at cutting down needless nesting which is vastly superior in terms of readability/eligibility. Can't really say there's anything superior about nesting ifs and elses together. I would go as far to say it isn't really a matter of preference, as one is just sloppy. At least if you're using the example given in the video.

    • @Voidstroyer
      @Voidstroyer Před 3 lety +4

      @sdsdsds dsdsdsdsds not necessarily. Depends on if in your recursion you are calculating the same thing multiple times, in which case you should use something like memoization to prevent this. A good example of this is Fibonacci with recursion. Fib(n) = Fib(n-1) + Fib(n-2). You are essentially calculating the same (n) multiple times so you should store the result in some kind of shared cache.

    • @Voidstroyer
      @Voidstroyer Před 3 lety

      @sdsdsds dsdsdsdsds You're welcome :D

    • @rickyanthony
      @rickyanthony Před 3 lety +2

      I know I've grown a little as a programmer because I finally understand comments like yours off the bat.

  • @michaelkjellander9370

    This is an incredibly useful tip. I have been doing this myself for many years, but not as consistent as you. I'm not sure it's necessary to do it like this every single time though, but I could be wrong.

  • @JamesWHurst
    @JamesWHurst Před 2 lety

    I'm appreciating your creating and sharing these video works. You do a lot of things right. And that's cool that you also point out competing videos: excellent positivity. Chapsas has a lot of videos, but I have a difficult time following his speech: it's a bit too fast.
    Your speech is fast too, but your annunciation is quite excellent and I have zero problem understanding you. I love that you present directly, quickly, and clearly.

  • @olx8654
    @olx8654 Před 3 lety +8

    Professors told me to do this good thing, but it wasnt till i started thinking for myself that i started doing this stupid thing.

  • @AccessAccess
    @AccessAccess Před 3 lety +164

    The problem with programming teachers is often they teach hard rules without explaining the intent behind the rules. So it just becomes blind adherence rather than something followed conditionally. A good example is the "one return per function". There is a good reason for this, sometimes. Other times, what he does with multiple returns is fine. When people understand the intent behind the "rules", then they know when they should be followed, and when they can be broken.

    • @diegop-s7943
      @diegop-s7943 Před 3 lety +15

      I’ve had some programming teachers show rules without explanation and some with explanation. What I’ve noticed that is the more advanced the class, the more in depth the explanation is. With your one return analogy, an introductory class might skip over the explanation to cover more content while a more advanced class will go into detail about unreachable code.

    • @beauxq
      @beauxq Před 3 lety +7

      It can be a problem with bad teachers. But it's also a problem with bad students. If they don't know the reason for the rule, they just assume that there isn't any reason for the rule.

    • @Vipyoshii
      @Vipyoshii Před 3 lety +30

      Another good examples is "stop using else". Hard rules are never good

    • @Stirdix
      @Stirdix Před 3 lety +28

      The two absolutely hard rules of code formatting:
      1. There are no absolutely hard rules
      2. No goto

    • @colinhoward2200
      @colinhoward2200 Před 3 lety +2

      Agreed - the MISRA rules explain all reasons why things should be adopted. These are not theoretical - they are effectively a case study of lesseons learnty over decades of issues that caught people out in real world sceenarios.

  • @Pearforce
    @Pearforce Před rokem +6

    Wont the extra function calls add overhead (however minimal) instead of just using else within the same function? It really depends on the language and compiler but unless the compiler optimizes code in a very specific way extra functions will just add unnecessary time to execute. But i also agree you need to gain readability at the cost of performance sometimes so its definitely a fine line.

    • @MattExzy
      @MattExzy Před rokem

      I've only ever messed around with Arduino stuff, but on microcontrollers (from what I've read) the 'if/else' way of doing things is generally preferred to switch/case statements or separate functions because of speed. For my feeble brain, I just stick to if/else because I can come back to project code many months or a year later and still understand my own writing. Also, the early exiting/returns make me nervous, since I'd like to test all available variables in a function first procedurally; I've been caught out doing the 'early exit' thing before.

    • @Martinit0
      @Martinit0 Před rokem

      Javascript compressors like Terser will eliminate those inner functions if they are simple enough. Generally, compilers offer "function inlining" optimization since decades.

  • @Neehize
    @Neehize Před 8 měsíci +3

    That second if-else looked totally fine to me. I've seen so many articles like "switch is bad" or "don't use else"... The reality is: DO use early outs and polymorphism whenever it improves the readability of your code but DON'T restrict your coding to a certain style because you believe it's the only viable practice. Switch and else are clean and relevant in many situations.

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

      A professional software is developed being restricted to well defined certain specific single style. That separates "professinal software development" from "coding".
      We had this world class coder in the company, he was winning coding competitions all around world. He could code insaly complex functionalities inline to single line. He was free to not restrict himself to certain style, specially once he was fired. His code was unmaintainable as everyone else struggled to read and understand it. Software development is a team sport, if you do not work together in same way as the rest of the team, you are of no value to any team.

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

      ​@@michaelholopainen2822 ​Does unconditionally banning else and switch look like "professional software development" to you? Of course we need a strict coding style and stay consistent with it (no matter if we're working in team or not!) But we should never forget the end goal: making the code look clean! And banning else and/or switch, as appealing as it sounds, goes completely against the idea of clean code.

  • @StCreed
    @StCreed Před 3 lety +47

    Dropping else-statements in favor of return statements, is pretty bad from the POV of computer science since it removes the ability of code checkers to prove that your code is valid. Mathematically, you can no longer prove the code always does what the requirements tell it to do. And this is my main issue with this approach. Readability can be solved by refactoring into more functions.
    If you don't understand nesting and the correspondence between provable code and correct code, the solution is not to throw out the else, but to get better at programming.

    •  Před 2 lety +1

      Huh? The transformation between the two styles is pretty mechanical.. Why would a checker choke on one style, but not the other?

    • @MarkRebane
      @MarkRebane Před 2 lety +5

      This is a fairly common misunderstanding. Yes, static analysis and code provability uses a single return point to make certain kinds of analysis tractable. However, regardless of how many return statements you use, every function only has a single return point. This guarantee comes from structured programming and isn't negated by code style choices.
      Consider that the control flow from any function call returns _to_ a single point, i.e. it returns _to_ the point from which the function was originally called. This is the single return point, not any of the zero or more return statements within the function. Even in the case of exception unwinding, control flow still passes as-if through that same single return point.
      Given that you can rearrange any code that uses early return statements to not use them, it follows that for any early-returning code with a flow graph G that there exists a homeomorphic / equivalent non-early-returning form of the code with a flow graph G'. Modern static analysis tools already handle such code without issue.

    • @hehefunnysharkgoa9515
      @hehefunnysharkgoa9515 Před 2 lety +4

      "Readability can be solved by refactoring into more functions." This, seeing the code in the video I was just thinking "wouldn't you just do function canDrink(person, country) { return person.age >= getLegalDrinkingAge(country); }" so that your code actually describes "to drink you need to be above the legal drinking age" instead of putting too much of the solution into one function?

  • @travis1240
    @travis1240 Před 3 lety +106

    Early returns can be good (as long as you've taken care of any co-concerns like events or logging and tracing). However I think the gymastics you need to do to get rid of "else" are usually not worth it. Most basic language constructs are avoidable if you're willing to put in the time and effort in doing something weird. Is it worth it? Sometimes but not usually.

    • @joschmo4497
      @joschmo4497 Před 2 lety +1

      Depending on the type of project you're working on, but usually not, it's more about flexing it seems.
      I've written code that could be described as clever but often times it's not necessarily better, it just looks out of the box
      Early returns are always good, why execute code needlessly?

    • @seraphina985
      @seraphina985 Před 2 lety +4

      @@joschmo4497 Eh, the CPU is actually executing exactly the same number of instructions in both the first example and the early return example. Either way after setting up the registers it does a compare, a conditional jump, sets a string pointer, calls another function, then returns unconditionally. Just in the first case the conditional jump fails so it falls through to the instruction in the next byte which is the start of the else block, in the second the conditional jump passes the instruction pointer gets overwritten and it executes inside the if block instead. The CPU really doesn't care one way or the other between these two it only starts getting extra workload once you start making parts of it into a new function call, a function call results in at least one instruction to put the current value of the instruction pointer to the stack, one jump to the functions address in memory, one instruction to pop the return address from the stack, one final jump to return. Obviously any additional parameters will require further instructions since the pointers to those values must each be put on to and then pop'ed from the stack also. So unnecessarily breaking down simple functions into very small parts is not particularly efficient.

    • @playmusic8056
      @playmusic8056 Před 2 lety

      @@seraphina985 if you want to optimize code, you need to take valid benchmarks before and after. As you say, the "better" version takes more steps to execute, and is otherwise just "different" not "better" as the same readability drawbacks from chained if/else statements exist in switch statements and in his consecutive short circuit returns.

    • @iFireender
      @iFireender Před 2 lety

      they're very useful in C, especially in embedded programming.
      As C doesn't have exceptions, you often return an error type that you define as an enum - something like OK and ERROR.
      If you were to save this to a variable, you're wasting cycles that can be very scarce in MCU - say, you're recording values every 10us on a system with 150MHz (or you're doing something in hard real time). Then you only have 1500 cycles to do your thing. Declaring then saving to a variable and recalling from a variable is already a few cycles - let's say around 10 for a low estimate. That's 'only' ~0.7% of your available cycles, but hey, those cycles could be used for other things.
      I still think that's a big problem with modern programming - most non-embedded things are so inefficiently coded that it doesn't even make sense to efficiently code. Write python? Unless you're using a C++ library such as numpy, just fucking do something - it doesn't matter anyways. Need something time critical implemented? implement it in C++. Javascript? Lol, don't even get me started.
      Most 'software developers' are just slinging libraries around to quickly accomplish their task (inefficiently), because we have the processing power necessary for it.

    • @playmusic8056
      @playmusic8056 Před 2 lety +1

      @@iFireender now you're arbitrarily defining efficient. The company pays the programmer to do work. Does it make sense to pay more for something that produces the same results a few milliseconds faster for a normal human workflow? That all depends on how the program will be used. Will it run billions of times per second, or only a few times per minute? Will it run on a constrained IoT device or on a server? Will it need to run on a user's click and respond immediately, or on a schedule where it can take 5 minutes and nobody will notice?
      JavaScript has its place as well. If you need a web app, or you are in a startup mentality of get it out now and fix it later, then it might make sense. If you want a backend service that's solid, executes fast, and will be maintained for a few years, then it probably doesn't make sense.

  • @angjiapheng
    @angjiapheng Před rokem +1

    My work is heavily inclined towards NLP, which has shit tons of uncertainty in the input. The reason I use "else" is to record anomalies so that I can update my code. But for the most part, I am taught to separate every function into modules, so that the code can be toggled on and off according to requirements, while much easier to fix.

  • @simonbaxter8001
    @simonbaxter8001 Před rokem +2

    Having spent most of my career (35+ years) writing c based embedded code for automotive and aerospace, the biggest part of coding has always been on reliability and robustness. Most of that revolves around code that has zero ambiguity and decisions that have a coding answer to every permutation. This ensures that you have considered all these and single return points from functions are usually better from code size as the local stack handling for the function call is done in one place. Also, creating more function requires bigger stacks and has a performance hit, so understand the end target before just removing keywords! For this reason, MISRA C/C++ was created for highly robust and deterministic code. Will be different for web based coding, but it's principles are extremely valuable and well worth a read.

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

      I've been at it about the same time... I've worked for various major aerospace and DoD contractors over the years... I seriously doubt that this kid has ever worked on a large project which required large numbers of developers in multiple groups at multiple companies...

  • @vadimslomonovskis5216
    @vadimslomonovskis5216 Před 3 lety +208

    It looks like my code before I learned about else :D
    It was mentioned already, but this approach may cause bugs and loose of logic. You also need to follow exact order of your if statements and may need to repeat same criteria for more complicated code.
    Also, it may be small difference, but in my understanding else allows to make code quicker. Every time you call IF, program need to check whether it is true or false. Else does not do so, because it already know the answer. Because you use more IFs and more likely repeat same IF conditions, your code slightly less efficient.

    • @fiveoneecho
      @fiveoneecho Před 2 lety +44

      Yeah, it kind of bothers me because there is more to code than being clever. The compiler will optimize things based on best practice and often times clever code is actually significantly worse. I used to do this kind of thing all the time before I got into compiler architecture. Turns out best practices are set by the people who designed the language (and compiler 99/100 times) and not usually by other clever people. Who’d-a thunk? xP
      That being said, creating unnecessary branches is not great and something to avoid. I would prefer this video be “You use else too much” rather than “You shouldn’t use else ever.” Guard clauses can be better for many cases.

    • @json9865
      @json9865 Před 2 lety +6

      I write code mainly for slow microcontrollers so I will probably continue to use else.

    • @NaudVanDalen
      @NaudVanDalen Před 2 lety +2

      He doesn't use any more if statements though.

    • @joschmo4497
      @joschmo4497 Před 2 lety +1

      Yes because else is unconditional, it does not redirect the flow of the program. I don't know if you've ever tried writing simple code in assembler but you can see how these conditional jumps translate into several operations.
      On a small scale program it often is not noticeable, segments of code that aren't optimal won't be observable but when dealing with a large set of data all these checks and jumps can drastically affect the speed of execution.
      I don't see how there's any advantage to getting rid of else condition unless you have such a problem that literally requires you to specify all possible outcomes. But more than that, you should worry more about nested loops

    • @ChrisPepper1989
      @ChrisPepper1989 Před 2 lety

      I think ur point about else being efficient isnt applicable to this example.
      It's the if that comes with cost. What you do following it, whether that be standard else or not, has the same cost.
      So for example "else" is coupled in the cost of the original if. But if you do "else if" your adding another if
      So if ur if will return or run the next block its the same computation whether u follow that with else or not
      Tagent but that'd what at low level ur aiming to remove every "if" in gles I often had to figure out something that would remove the if by way of maths for example you might try and replace ur if with something that would nullify that part of the equation (e.g multiple the expression by your boolean)
      There is also an interesting quirk/trick I've seen in c++ with empty if blocks and boolean functions that I'll have to dig up lol but I wouldn't recommend it lol

  • @ponypapa6785
    @ponypapa6785 Před 2 lety +245

    Generally speaking: yes. extracting complicated code in its own function is a VERY goot idea.
    But:
    MOVING RETURN ON THE SAME LINE AS THE IF DOES NOT REMOVE NESTING.
    this merely HIDES the nesting. Also you had 2 levels of nesting, now you have 1 level of nesting (because of the initial guard clause) so, concerning nesting, you did not really change that much.

    • @dametocosita4994
      @dametocosita4994 Před 2 lety +5

      I think you missed the point.

    • @ME0WMERE
      @ME0WMERE Před 2 lety +14

      @@dametocosita4994 he was simply making a point on the video's first point

    • @DejitaruJin
      @DejitaruJin Před 2 lety +22

      It also didn't improve refactorability at all. As someone who actually teaches people to code, I am... rather concerned that his threshold for a function being "too big and complicated" is "it contains an else".

    • @WilliamLDeRieuxIV
      @WilliamLDeRieuxIV Před 2 lety +9

      > *extracting complicated code in its own function is a VERY goot idea*
      Functions are created to prevent duplicate code (a code block, algorithm, etc) and not for cleaning up code in one place.
      If the created function is only called/used in one place, then it shouldn't have been created.

    • @TreezTV
      @TreezTV Před 2 lety +1

      @@DejitaruJin it's an example function that is made simple for viewer comprehension. I think the meaning of the video is to build cleaner coding practices and to think about possible solutions with a different perspective.

  • @MattOatesUK
    @MattOatesUK Před 2 lety +4

    The main thing missing from why its worth doing this is unit testing. I guess JS doesn't have a huge testing culture, but that's one of the bigger reasons. It often takes more, and more complex test scenarios to get all the paths of nested if/else blocks. But with the smaller function with two ifs you know exactly what and how to test passing in just an integer not an object.

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

      The argument is strong, but if the logic is the same and doesn't hurt badly the performance, it's also too strong to avoid like hell "else". In pursue of that, people use big hash tables everywhere, multiple key/values, it's nice, it's beautiful. But many times code turns not as readable as a simple vanilla if/else for every people you expect to work on that code.

  • @matheusjahnke8643
    @matheusjahnke8643 Před 2 lety +2

    Doing single return is useful in some languages.
    Like:
    setup()
    doStuff()
    cleanUp()
    return()
    If there are multiple returns, then you should remember to cleanUp()
    Javascript is usually not one of them; If this was C code where setup() involves memory allocation and cleanUp() involves freeing the allocated memory, this would be useful. One time I even saw someone do an early return without freeing the mutex;
    Scopes and destructors usually deal with that kind of problem in modern languages - if they exist. The example you did, doesn't really involve that, so single return isn't really required.

  • @PaulMurrayCanberra
    @PaulMurrayCanberra Před 2 lety +31

    @4:13 the "single return policy" is a legacy of assembler programming. The purpose was to make sure the stack always got unwound properly.

    • @MagicGonads
      @MagicGonads Před 2 lety +1

      returns in higher level programming, if they even get compiled to assembly before execution anyway, will get abstracted into comparisons that point branches at a single return.
      (same with intermediate languages that have a return atom like MSIL, write C# code with multiple returns and the MSIL it is built into will probably still only have one return instruction)
      so if this even still matters for assembly, you aren't writing assembly, there's no reason why the system that produces assembly from your code has to trust you to perform a literal return at the exact position that you told it to (because these languages are able to use jumps and breaks to get around, and that isn't an anti-pattern because of how low level they are)

    • @reiniertl
      @reiniertl Před 2 lety +4

      @@MagicGonads I have to confirm what you say, but I agree with you. At least in C, when I look at disassembled code, I see returns always branch to the epilogue of the function (the code you don't see when writing a function) where things get tidied up for return. So I don't see that having multiples return is a problem for any modern compiler, nor I see a problem with using else, or any other keyword or statement.
      Some programmers jump like crazy if you just mention that C has "goto" they always tell you "you should never used" because branching like that is a really bad idea. I always think "here is another programmer who has never looked at disassembled code or has no idea of any ISA". I remember attending a lecture from Donald Knuth where someone asked about this particular issue, in the end he not only said that he used "goto" multiple times in the past but also stated that any statement or logic expression can be dangerous. He just mentioned some study he conducted with his students back in the 70's, so no programming technique is good or bad, just depends on skills and scenario.

  • @minecraft4life525
    @minecraft4life525 Před 2 lety +56

    As a person who's been doing this for 4-5 years at this point, I've learned that if something is better, but inconsistent with the existing code, then it's simply not better. Imnsho guard clauses are objectively better for most cases. But gl&hf teaching that to people who have been coding with nested stuff for years. And no single convention is worse than mixing 10 different ones. Exact same thing can be said for immutability.

    • @javier.alvarez764
      @javier.alvarez764 Před 2 lety +1

      true uniformity and consistency with the current code base is far more important. experience developers emphasize upon design patterns, but really, what they should give importance is not doing anti-patterns.

    • @AaronBynum
      @AaronBynum Před 2 lety

      This has been my experience as well.

    • @flowerofash4439
      @flowerofash4439 Před rokem +1

      this is the worst part of javascript, you can do even the very simple logic in many ways, too many syntactic sugar, too many freedom, make it painful to read. same shit diferent code.
      imagine a programing language so bad that people make another language (typescript) just to fix it

    • @xX_dash_Xx
      @xX_dash_Xx Před rokem

      "the system sucks so I'm going to write worse code instead of trying to fix it". I really suggest you try to push code cleanup on your projects, it is an integral part of development IMO

    • @minecraft4life525
      @minecraft4life525 Před rokem

      Good luck convincing business people (who are the ones distributing the money at the end of the day) that you're going to spend a day/week/month to rewrite code that has already been tested and known to work, just so your if-s are better or you distribute it better. Then have it retested... Very unlikely.

  • @mitchlee3724
    @mitchlee3724 Před 2 lety

    You can still implement a guard clause and have a single return. Wrap your code block in a while(0u) loop and use Break staments to force an early exit.
    Within embedded systems there is a standard called MIRSA C of which one of it rules stipulates that every function must have a single return.

  • @OJB42
    @OJB42 Před 2 lety +2

    I agree with you regarding the guard clause; I use those myself a lot. I hate too many layers of nesting! I have no idea why anyone would say to only use a single return. I think it is clearer keeping the inner if as a series of if/else in many cases, though.

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

      There are a variety of arguments to be made for a single return.
      One is that it allows you to put final things at the bottom of a function while debugging, just before returning.
      This includes changing how it returns, e.g. changing from a single value to an object.
      With a single return, this is trivial.
      With multiple return statements nested throughout, you need to do it for all of them.
      It can also be useful for cleanup code if needed.

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

      @@jeffreyblack666 Agreed. There is never one answer which works in every case. It's always a matter of making the right trade-offs for each situation. That's what makes programming an art as much as a science.

  • @bruhe_moment
    @bruhe_moment Před 2 lety +50

    Using early returns in place of else only improves readability in very few cases. Most of the time, it just makes it more difficult to tell that code is conditional.
    I cannot tell you the number of hours I have spent trying to figure out why some code wasn't running, only to find a "return" hidden deeply in an earlier if block.

    • @jasonhoerner9954
      @jasonhoerner9954 Před 2 lety +4

      I worked at a company where early returns were banned in the coding standards, for that reason.

    • @JimOHalloran
      @JimOHalloran Před 2 lety +5

      Yeah, agree. This is a real pain especially when maintaining legacy code. You find what seems like the most appropriate place to make your change, only to find that the new code doesn't run sometimes because of the early return buried somewhere.
      I favor an approach where you use guard clauses to sanity check the parameters to.a function early on, and return early if you can't proceed. But once your function gets into doing "real work", it should run through to the end with a single return point.

    • @Telee_Pawt
      @Telee_Pawt Před 2 lety +1

      "hidden deeply" There's
      the problem :-)

  • @sciverzero8197
    @sciverzero8197 Před 3 lety +20

    I can't tell you the number of hours I've wasted before trying to make guard clauses work for hypercomplex situations when a nested branch would have been the simplest and most efficient use of my time.
    Guard clauses can save you a lot of headache, but they can also create confusion in your code and waste a lot of time and just as importantly, space and duplicated code, under certain circumstances.
    This is a god technique to employ when possible, but never let your preferences get in the way of actually completing the task.
    Code that runs is always better than code that doesn't. Everything in moderation.
    PS: Also any time your code gets complex enough that it _could_ be non-obvious... just leave some comments in. Some people comment too much, others too little, and have strong feelings about either extreme... but frankly, comments can be a godsend when working with a base you haven't used before or in a long time. Just make sure your comments actually mean something. Sometimes its better to comment your code and use uglier branches than to write an excellently beautiful function that has the next guy jumping back and forth over a billion different functions and methods trying to understand where the single piece of behavior they're trying to alter is. Having everything in one place, but properly documented, can be easier to work with at times.

    • @TheSnHIMshow
      @TheSnHIMshow Před 3 lety +3

      That "next guy jumping back and forth over a billion different functions and methods trying to understand where the single piece of behavior they are trying to alter is".. hits too hard.. omg the times ive opened a project and everything looks clean and neat but then this function leads to this file which in turn imports this file that imports that file isnt worth it. I think that's why even microservices are being rolled back to/into monoliths, or at least larger more manageable microservices

    • @Kiev-en-3-jours
      @Kiev-en-3-jours Před 3 lety +1

      If you need to add a comment usually it is a sign you should refactor your code (use better function names, move code to external functions, etc...).

    • @fryphillipj560
      @fryphillipj560 Před 3 lety +1

      ​@@Kiev-en-3-joursI get where you are coming from, but I imagine this is exactly what leads to: "next guy jumping back and forth over a billion different functions and methods trying to understand where the single piece of behavior they are trying to alter is"

    • @Kiev-en-3-jours
      @Kiev-en-3-jours Před 3 lety

      @@fryphillipj560 Well, that is just not what I am experiencing with my code. I know exactly what functions do since the name of a function is self explanatory. And each function is located in the feature or category object they belong to. If you organize your code properly I guaranty what you describe just doesn't happen. Sure you jump a lot but a jump is just a fraction of a second in visual studio code.

    • @Amit-sp4qm
      @Amit-sp4qm Před 3 lety

      @@Kiev-en-3-jours it happens 😁
      Coding is not in small steps for me .. I always keep a bigger picture of what's happening and the code in front of me helps keep that picture .. so even if the function is a click away in some code editor .. it's still distracting ..

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

    This is what I have been doing for a long period of time without knowing it. I had an scenario where there were more than 7 conditions in the if part and it was difficult to follow.
    What is did it the elimination of each condition one by one and immediately the code looked much cleaner and readable. The addition of comments on each condition just improved it so much.

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

    i had heard the 1 return per function, but i dropped that pretty quickly when i realized that multiple returns provided code "safety" to terminate when i wanted it to and prevented the chance of unintended logic flow continuing past where it "solved" the question of the function.

  • @shadowlifter
    @shadowlifter Před 3 lety +111

    Code is for humans. So I write to be readable even for another person, a year or more later. Most times condensed code is harder to read and some times might lead to problems. I want to make my life easier, I don't want my colleagues to always ask me "what do you mean by this?"

    • @SoraFromIndia
      @SoraFromIndia Před 3 lety +21

      If you want to do that at the cost of writing inefficient code then you really need to think it all over again. It is basic knowledge that nesting increases the complexity of a code (yes Ik it is still done in tons of cases). If there is a way that you are able to avoid it then going for it is the best thing you can do. Code is supposed to advance with time and it will keep getting complex with time as well. It is really a bad mindset to not wanting to improve and stay in your comfort zone just so that it doesn't become too much of a task to keep a tab on what's going on.
      Humans adapt to change as we always have. Not just humans but every organism that are thriving currently were able to adapt to changes and that's why they are alive.
      Constant improvement and wanting to be more efficient is a mindset that is extremely important if you don't want to be a typical C++ developer who just wants to stay at their comfort zone and keep writing the same shite every day for the rest of their lives cuz they are too afraid to learn something new as they are way too comfortable.
      But then, that's just my mindset. I understand if you don't get along with it and no offence from my side. Just said what I thought was important. In no way I want to start any sort of argument or what not.
      Peace.

    • @dariosucevac7623
      @dariosucevac7623 Před 3 lety +2

      @@SoraFromIndia Damn, that's inspiring. Thanks.

    • @SoraFromIndia
      @SoraFromIndia Před 3 lety

      @@dariosucevac7623 no problem mate :)

    • @andli
      @andli Před 3 lety +9

      In the example in the video, as long as the functions are named properly and according to convention, the code is more readable than with nested if/else clauses IMHO.

    • @SoraFromIndia
      @SoraFromIndia Před 3 lety

      @@andli True

  • @adlibrium
    @adlibrium Před 3 lety +13

    Else has a place, just like guard conditions have a place. If your entire function is basically a guard condition what is it guarding? It reminds me of how when someone learns something new, they try to find creative ways to use that new thing and end up using it in a way it isn't intended. To quote Abraham Maslow, “I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail.”

    • @howardbaxter2514
      @howardbaxter2514 Před 2 lety +1

      Very true. Use various scripts and classes where it makes sense. Use functions where it makes sense to use them. Use else conditions where it makes sense to use them. To just eliminate else altogether is pretty stupid, imo. There is no right answer on when and when not to use either, but use common sense when approaching both.

    • @howardbaxter2514
      @howardbaxter2514 Před 2 lety

      And this is something I think about when I program. How can I make my code in such a way where I can make quick changes in the future while understanding its impact on the overall outcome? Should I create a separate class so I can readily import it to various other scripts? Should I break up my code into chunks so I can reasonably call upon functions multiple times, instead of needlessly creating one that will only be called upon once. Should I use an else if statement or a nested if statement when handling various variables? These are all questions I ask myself, and I know the answer isn’t always the same across the board.

  • @briankarcher8338
    @briankarcher8338 Před rokem +2

    Good conversation topic. Cleaner code is something everybody should strive for. Some languages can make this code even simpler. Notice the reuse of the "age" variable and if statements. Some languages now allow relational patterns in switch statements.
    In C# for example you can now do this:
    var res = num switch
    {
    >= 4 => "It's >= four",
    3 => "It's three",
    0 => "It's zero",
    < 0 => "It's negative",
    _ => "It's something else"
    };

  • @NoirMorter
    @NoirMorter Před rokem

    I've begun doing that with my coding as well it's been very useful to me and helped with my debugging. I avoid else's where its best and I use multiple returns when the situation likewise calls for it. They're both very helpful tips. Also, you can do this fairly easily with C#.

  • @jimbeaux4988
    @jimbeaux4988 Před 3 lety +11

    I like the guard clauses, especially right at the top of the function where it's easy to spot.
    I saw a lot of beginners get into trouble by NOT using the else. They would write code that only checked the true condition with no thought about what happened when it was false.

  • @somabiswas2629
    @somabiswas2629 Před 3 lety +41

    Switch cases: Allow us to introduce ourselves

    • @grantorino2025
      @grantorino2025 Před 3 lety

      How would you rewrite the same logic with switch case?

    • @anselme198
      @anselme198 Před 3 lety

      @@grantorino2025 with languages that support pattern matching

    • @LSDsuperfruit
      @LSDsuperfruit Před 2 lety

      @@grantorino2025 function canDrink(person) {
      switch (true) {
      case person?.age == null:
      console.log("You are not a person")
      break;
      case person.age < 18:
      console.log("Nope")
      break;
      case person.age < 21:
      console.log("Not in the US")
      break;
      default:
      console.log("Yes")
      break;
      }
      }
      const p = {
      age: 22,
      }
      canDrink(p)

  • @rumasakvedis4422
    @rumasakvedis4422 Před rokem

    It is one of the tricks I learned very early at the beginning of my career and I've been grateful ever since. It is so much more natural, no policeman would interrogate a suspect for 20 minutes before realizing that he's actually talking to a dog. So get those easy to check conditions out of your way first. It also makes it far more easier to refactor code by adding conditions or shuffling them around if you realize that a certain check is very expensive compared to others. No need to get a dog's license ID checked. Or when you realize that it's probably better to put some long expression into a separate method/function instead.
    Once, I went to an extended leave, and when I came back, a colleague had replaced all instances of this pattern with elseif.

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

    I've never made excessive usage of `else`, mostly because it can introduce unpredictable side effects. There are exceptions (no pun intended), but in general, avoid it. Instead use guard clauses. I use these all the time. I try to anticipate errors as much as possible, and use try-catch sparingly and where warranted. Uncaught exceptions can actually be a good thing, especially if they aren't breaking key functionally, but this MASSIVELY depends on the nature of your app. Whenever the physical safety of people is involved, testing infrastructure is absolutely critical and likely a matter of life and death. DO NOT TAKE CHANCES WITH LIFE!!!!

  • @ArchaeanDragon
    @ArchaeanDragon Před 3 lety +29

    I guess it is just what you prefer. For me, the "better" function is actually more complicated and less readable. *shrugs*
    Also, lots of little functions are less speed (and often, space) efficient. Control transfers (jumps, branches, calls, etc) are often more costly to execute than a simple stream of instructions.

    • @KlebinDaBoca
      @KlebinDaBoca Před 2 lety +3

      > Also, lots of little functions are less speed (and often, space) efficient. Control transfers (jumps, branches, calls, etc) are often more costly to execute than a simple stream of instructions.
      That's... Debatable.

    • @redstonerti9918
      @redstonerti9918 Před 2 lety +1

      The speed decrease is so small that it literally doesn't matter

    • @KlebinDaBoca
      @KlebinDaBoca Před 2 lety +6

      @@redstonerti9918 That's also debatable. Micro optimization has its place.

    • @timnonik2736
      @timnonik2736 Před 2 lety

      @@redstonerti9918 thats bs, in some cases every little bit is a bit to much

    • @redstonerti9918
      @redstonerti9918 Před 2 lety

      @@timnonik2736 Maybe if you are writing extremely optimized and high performance code for something specific, but for a web developer it definitely doesn't matter

  • @harshilpatel387
    @harshilpatel387 Před 3 lety +211

    this is more of a style thing versus a *actual* good coding habit

    • @Kevin-lh6xu
      @Kevin-lh6xu Před 3 lety +1

      Can you elaborate. I just want to know what you mean not trying to attack :3.

    • @harshilpatel387
      @harshilpatel387 Před 3 lety +29

      @@Kevin-lh6xu seems like he is simply rearranging and splitting his original nested if-else block. What i mean by style is that one could easily elect to say use a Switch block, ternaries, null coalescing etc to accomplish the same thing. Sort of at the end of the day comes back to ones coding style vs a wrong and right way of doing things (similar to how if multiple people sat down and wrote an essay... we would all for the most part structure our essays by paragraphs differently/logic to accomplish the same thing)

    • @gabrielyea
      @gabrielyea Před 3 lety +11

      @@harshilpatel387 I have worked in some big projects (hundreds of classes) and else and switch case statements are the critical places where bugs are introduced. It is good and common practice to avoid them and use little processing blocks. Switch cases can always be replaced by a better pattern and are reserved for the factory pattern.

    • @daves.software
      @daves.software Před 3 lety +3

      @@gabrielyea "Switch cases can always be replaced by a better pattern and are reserved for the factory pattern." Please implement Duff's Device using the factory pattern.

    • @dcnumba20
      @dcnumba20 Před 3 lety +2

      Nested ifs and loops can get real nasty, so the functions can really help clean things up. But past that point you're probably right, unless there's some branchless path you can take which would definitely speed up your program.

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

    Just the fact that you can understand the refactored code is huge and absolutely worth it!

  • @stephanweinberger
    @stephanweinberger Před 2 lety

    Not only does 'else' lead to deep nesting, it also tends to "tatter" code.
    Take your example with setting a variable with the message and then printing it at the very end - and that's in a very simple function. Now imagine a more complex function that checks for several different conditions, all the while setting and updating that variable: not only is it inefficient to assign values that get overwritten just a few lines further, it also makes tracing what actually happens much, MUCH harder.
    Avoiding 'else' and using guards/early return automatically forces one to structure the code in a way where one thing is handled in exactly one place (and then put it into a separate function as next logical step).
    I'm just working through a very old codebase that extensively uses else... there's nesting sometimes 7 or 8 levels deep (and sometimes even without curly brackets, e.g. when the nested part is a loop - with more nesting inside, of course - so it's often even hard to tell where a block actually ends)... also the same things are often checked and re-checked numerous times, or variables changed 20, 30 lines down the line, completely changing the result... it's a nightmare!

  • @seraphendipity
    @seraphendipity Před 3 lety +37

    Cutting through YT 10-min Padding:
    * Use guard-clauses instead of else's
    * Reject Single-Return, Embrace Multi-Return
    * If nesting, consider making a function for it instead

    • @colinhoward2200
      @colinhoward2200 Před 3 lety +2

      Seriously - do not embrace multi-return. I have given an example above where you can have one return and no elses

    • @bokoloaranyfa3824
      @bokoloaranyfa3824 Před 3 lety +1

      "Single-Return"
      Single-Return is a necessity for many areas. When intensive logging (entry, exit...) is your only friend, multi-return is the last thing you want to use.

    • @JohnSmith-xf1zu
      @JohnSmith-xf1zu Před 3 lety

      Multi-Return is good for things like guards at the beginning. Other than that, it should be used carefully and logically so as to keep the flow of a function readable.

    • @colinhoward2200
      @colinhoward2200 Před 3 lety

      @@JohnSmith-xf1zu So tell me then, why even guards are not allowed to be used for control systems for nuclear power stations and aircraft? They are explicitly forbidden. Perhaps all these people extolling the use of them have more experience of stopping things going horribly wrong in disasterous scenarios - I doubt it though :)

    • @colinhoward2200
      @colinhoward2200 Před 3 lety

      @@JohnSmith-xf1zu The real thing is this is in safety critical software it is not even written like this. Most problems are first modelled as a finite state machine - there are no if statements really. The problem is modelled as an FSM using a UML, or even Yourdon. You do not encounter guard statements. All routes are caterred for, and fall out of invalid event and state combinations.
      The whole issue with software development and naval gazing on issues such as this, is they have not actually designed the code properly in the first place, or used best practices from software that needs to be "safe", and also actually testable.
      It is easy to start programming and look clever. It is way harder to think harder and design. It is what annoys people who develop software when functional safety is required hen too much emphasis is given to algorithms.
      For example, examples given for Google / Facebook interviews all rely on recursion. If you rely on recursion in say a fly by wire aircrafy system - it is not determinstic, and you could be flying along and you blow the stack - end net result - plane falls out of the sky!!!
      So SC engineers have to follow rules - which are lessons learnt from people making assumptions. Sooo design first, do not use multiple returns or guard statements, and do not use recursion - if you are clever enough you can linearise recursion algorithms in a fixed memory space. And so on and so on - the MISRA rules are always worth a read.

  • @anjuro
    @anjuro Před 3 lety +91

    I think there's definitely something to minimizing nesting (at least when it improves the control flow) but I'm not sure that creating a bunch of tiny functions for every little thing is the way to do it. It cleans up the main function body, sure, but the way I see it if you're reading the function body there's a decent chance that you want to look at the contents of all those helper functions you defined to keep the code "clean".
    It's agony when you're trying to find a bug etc. and every function just calls a bunch of other tiny 3< line functions. Honestly I prefer a chunky function here and there to a fractured codebase that is impossible to read serially (not that the example you showed fits in this category but I think that's what you eventually end up with when you apply the principle of defining helper functions gratuitously anytime you do anything). It's a balancing act of course but I just thought I'd make an argument for the opposite POV since you didn't really touch on that.

    • @jimbo573
      @jimbo573 Před 2 lety +17

      100% agree. Big functions can be unreadable, sure, but so can big call stacks. Also, functions that only have one caller can give the false impression that the two parts are logically independent when in reality they are coupled.

    • @baka_baca
      @baka_baca Před 2 lety +9

      Definitely agree in taking caution with over-breaking-down functions into other functions. I've seen this in extreme cases in the wild where every single part of every function was broken into more files and functions, including the helper functions themselves! It took hours to days to do small refactors and bug fixes.
      This is in an API which I took the time to refactor one of the endpoints. Went from over 18 files and hundreds of lines of code and fragmented logic, to about 4 files that were maybe 100-150 lines of code total. Turns out the helper functions just weren't really helpful.

    • @graffhyrum
      @graffhyrum Před 2 lety +4

      Doesn't every IDE have a 'go to declaration/usage' hotkey? I find it super easy to navigate the abstraction layers as long as all the helper functions have good names. If it really becomes a problem then just inline the function to work on it and re-extract the helpers when you get it working again.

    • @MaxMustermann-bm7qt
      @MaxMustermann-bm7qt Před 2 lety +1

      To me, everything that has a much higher/different level in detail gets it's own function or code that repeats. I use methods to keep the specific subfunctions grouped to the main aim. works ok-ish.

    • @fnorgen
      @fnorgen Před 2 lety +7

      @@graffhyrum The point is that it is off course situational. A big function is not automatically hard to read as long as the control flow is nice and obvious. It is also perfectly possible to make a function much harder to read if it is broken up into poorly though out helper functions, to the point of creating a labyrinth of function calls that only serve to obscure the actual flow of the program rather than just abstract away the gritty details.
      When I was a noob I was overly zealous about never letting any function get too long, and ended up with a mess of hard to explain helper functions scattered all over the place. The solution was to just accept that sometimes long blocks of code are perfectly fine as they are.

  • @AlShwan
    @AlShwan Před 2 lety

    Imagine a function is like walking down the stairs, a premature return/break is like jumping out of the window, not a good way to get down

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

    It’s nice to understand the affect of branching statements on your code’s performance. Using / not using if-else isn’t usually a performance optimization.
    It’s a valid tool, that has its benefits. Replacing if-else with any other type of statement will also have its affects on performance.
    I low-key hate these videos that tell people to adopt a new style into their code. Just write regular code..
    To elaborate:
    If-else statements perform similar to switch statements - after about 6 comparisons, it’s recommended to switch (assuming your working with switch-valid values).
    It’s not uncommon to write a method that requires a conditional, which might return a result.
    You can use the syntax:
    return (condition)? if_value : else_value;
    Which can serve as a single-line statement, that could be used in lambdas, loops, or maybe a call to “this(…)”.
    Else blocks might be necessary for a specific flow you might want. If you have a method:
    int f (x) {
    if( condition )
    return 0; // constant value
    else
    return f(x+1); // recursive call
    return x-1; // not constant value
    }
    When you say you don’t use else. I just think you’re coding to the fullness of your capability.
    Some people try to avoid branching statements with arithmetic expressions : iff it is possible to do so - which can help the compiler. Assuming your running some pretty expensive code. That’s such a trivial situation too. Usually, we might look at fork-join pools to help optimize performance like that.

  • @skylerdjy
    @skylerdjy Před 3 lety +86

    me an intellectual: everything after an if return is an else.

    • @HrHaakon
      @HrHaakon Před 3 lety +1

      Yes but also no, but also yes? XD

    • @gregr28
      @gregr28 Před 3 lety +5

      I was think the same thing. You're just replacing "else" with "return".

    • @hil449
      @hil449 Před 3 lety

      It improves readability tho

    • @gregr28
      @gregr28 Před 3 lety +3

      @@hil449 does it really? Your entire decision tree is on the same level as the rest of your code, regardless of how many logic levels deep you are. That's the antithesis of readability

  • @tvalid880
    @tvalid880 Před 3 lety +4

    I was taught to use else in my first couple introductory programming classes. But when I took data structures and algorithms, my professor advised us to try not to use else. It was hard at first, having to get creative with different methods. But after using it for a while (just like recursion), I totally saw the value in using it and it totally made my code way better.

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

    Like any construct, "if then else" can be misused, but that doesn't make every use bad. Even "go to" can be used clearly in some circumstances.

  • @ShadSterling
    @ShadSterling Před 2 lety

    In order to understand how a program works, you have to have a mental model of how every function(/method) is used and relates to other functions(/methods). What you're doing is moving complexity out of individual functions and into the call graph. This does not reduce complexity, it just moves it. I'd rather separate functions that are needed in multiple places, and let the complexity of any function be whatever it needs to be - so I can build a simpler mental model of the call graph, and only have to think about the internals of any function when I'm doing something that touches that function. Guard style vs nesting style is just a style choice, with editors that do collapsing, maybe some tl;dr comments on blocks, and tab stops set so you can just see how deeply nested you are, navigating within one big function can be easier than navigating back and forth between a dozen tiny functions

  • @blisterfingers8169
    @blisterfingers8169 Před 3 lety +15

    "This entirely subjective matter is FACT!"

  • @mg-by7uu
    @mg-by7uu Před 3 lety +81

    What happens if later on there's a bug with your conditional that would typically show up inside the else clause? Since you don't have one you'll be dealing with a silent error and if you don't remember what you did before you could be in a world of hurt.
    There's a reason the ternary operator enforces it: You should always have an else statement.

    • @joshua43214
      @joshua43214 Před 3 lety +7

      For straightforward programmatic code like this, it is not really needed since age can be well defined, and returned alongside the other outputs either for debugging or added to the console output "you are xx years old, you may..." so that it is clearly visible. In a case like this, one should also add a clause that demands that p be an integer, and below some reasonable number, and then raise an exception on failure.
      It gets trickier with multiple variables, especially when they are mixed values and mixed formats. I work with big data, and most of my code does nothing more than validate the inputs as valid.
      The other important aspect of exiting early is that it is much more efficient. Performing a bunch of Booleans on 10's of millions of data points runs slowly even on the Super where I work. Put the most common exit condition as close to the top as possible, and move on to the next datum.

    • @mg-by7uu
      @mg-by7uu Před 3 lety +2

      @Erich If your if statement has faulty logic it could evaluate to false and continue until it reaches the else statement.
      If you don't have an else statement you won't be able to quickly identify which condition is failing. I've seen it take hours before so all my conditions have an else clause.

    • @mg-by7uu
      @mg-by7uu Před 3 lety

      @Raymond Andrews Hey thanks I learned something new!

    • @meaningless4845
      @meaningless4845 Před 3 lety

      That's why we have debugger I guess?

    • @dynpallomah5918
      @dynpallomah5918 Před 3 lety +1

      @Raymond Andrews No, not exactly. Think about it, if condition is false, and the ternary operator can only output when its true, then what happens? Not all programming languages have the concept of JS undefined, maybe the output shouldn't be undefined either. Your argument on the operator's name is unnecessary and it could be called something else if you wish.

  • @FatLingon
    @FatLingon Před 2 lety +2

    At 5:45 you introduce the result-variable, and at 6:15 you add an else if back in. Instead you could change the order of the if statements, so that you check for "< 21" before you check for "< 18" thus removing the need for "else if" cause the "< 18" will overwrite the result if it is true.

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

    That’s so smart. I never thought of that as an option.

  • @KanoKendama
    @KanoKendama Před 3 lety +28

    I personally love to use switch-case. No matter how many conditions, you can pair them around and have the code be both explicit, safe and clean.

    • @AllanSavolainen
      @AllanSavolainen Před 3 lety +7

      Nested switch cases with gotos are the best!

    • @farrael004
      @farrael004 Před 3 lety

      If you're building larger systems that will require long term maintnance switch is probably worse than using a string of else if due to how rigid it gets when multiple systems need to interact with it. Think about it, you need to explicitly state what to expect in a case, then if you need to change one of the cases, then you'll also need to change it for all other systems.

    • @inigo8740
      @inigo8740 Před 3 lety +1

      Sadly, python doesn't have switch-case structure yet. For me, this is very good advice.

    • @JohnSmith-xf1zu
      @JohnSmith-xf1zu Před 3 lety

      I had a prof in college that wrote a subroutine that "simplified" the logic for us. The "simplified" logic had multiple nested switch statements up to 3 level nesting....
      He taught primarily engineering and not much comp sci.

    • @AngelHdzMultimedia
      @AngelHdzMultimedia Před 2 lety +1

      @@inigo8740 It was added recently. It's called match/case.

  • @devsauce
    @devsauce Před 3 lety +110

    My friend has been told by his college teacher not to use break or continue in the loops because its "bad practice" and instead use true / false flags. I would take everything you're being told in college with a grain of salt...

    • @genechristiansomoza4931
      @genechristiansomoza4931 Před 3 lety +30

      Continue using break and continue keywords. In real world, client will not ask for that "Did you use break or continue in your loop?" or whatever. As long as your program gets the job done then you're good to go.

    • @TodorescuProgramming
      @TodorescuProgramming Před 3 lety +3

      I guess to use break might be a bad practice, I rarely use it, instead use a lot of continue.... if you think about it, why would you wanna break a for loop ? doesn't make sense only if you're looking for something in it, in that case you use a .find() ...
      Might be if some state changes in that case you want to run an recursive function to navigate an object/array and have a guard clause

    • @jonatlop3816
      @jonatlop3816 Před 3 lety +28

      @@genechristiansomoza4931 I consider that you should be cautious about giving those advices. Of course, a stakeholder will not care whether you clean code or not, it is a matter of maintainability of the software: the code you write has repercussions to the team/company you work with if it does not allow extensibility/reusability. I suggest you to read about refactoring and clean architecture to gain insight into this topic. Best regards!

    • @genechristiansomoza4931
      @genechristiansomoza4931 Před 3 lety +3

      @@jonatlop3816 I did not give bad advise. I just said not to be afraid of using break and continue on loops if necessary and if it gets the job done. Refactoring code is a different topic.

    • @tomg0
      @tomg0 Před 3 lety +20

      Continue and break are very widely used and useful. In many cases, replacing them with a Boolean in the loop will be tedious and cluttered. Don’t listen to those people.

  • @kuriel07
    @kuriel07 Před rokem

    for small set of state if have no problem with using if-else, larger set of state i use table, need more readibility, use macro/inline, prefer macro instead of function because it's fast, executed on compile time, easy to modify and can access local variable of caller function

  • @manankpatel2759
    @manankpatel2759 Před 9 měsíci +1

    Those who have issue with what functions might return or whatever, use typescript. And everyone is saying that else in his code didnt have to be removed etc..., but this was just an example, in a real world scenario, sometimes nested if else can get really messy to understand, its upto you to determine when its time to simplify the mess, in a code like this we won't have to do such things but again its just an example of how to improve the code not an example of what kind of code to be improved.

  • @StefanReich
    @StefanReich Před 2 lety +58

    Actual programmers: "I created a software that solves a problem"
    Fake programmers: "I don't use the else keyword"

    • @valletas
      @valletas Před 2 lety +1

      This is such a weird thing to me as a biggener in programing because else is so easy to understand and id the language suports it you could also use stuff like elif to make things even better if necessary
      I can only imagin how spaghett the code will be without using else

    • @SmallSpoonBrigade
      @SmallSpoonBrigade Před 2 lety +1

      His first example was an abuse of the else keyword, not optimistic about the rest of the video. Dumping everything else to a result based on not being any of the previous options is somewhat risky. One of the best reasons to use the else keyword is to log when a response or result wasn't in the list of expected cases. It's also not a bad spot to deal with issues that could lead to security issues by specifically using the else to catch everything else and deal with the potentially bad results there, rather than hoping that they don't break the code in ways that's more problematic than normal.

  • @Zeakuro
    @Zeakuro Před 3 lety +7

    All programming techniques have their place. Sticking to or avoiding certain techniques are limiting. Instead we should try to use the best technique for a particular use case. In the case of the code shown I would have rather used a switch statement as I think this is a more clean approach. Multiple If statements, or If Else statements also have their place though.

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

    else statements have their place. Its just if things start getting hairy with them all over the place, then there's probably a better way. Sometimes a new function is the solution, sometimes a case block is. Just depends on the program requirements. But most of all - less is more as long as its human readable