"Stop Using if else if else In Your Code!" | Code Cop

Sdílet
Vložit
  • čas přidán 22. 10. 2023
  • Become a Patreon and get special perks: / nickchapsas
    Hello everybody, I'm Nick, and in this video, I'll show you some really questionable advice around if else statements and ternary statements in C#.
    Workshops: bit.ly/nickworkshops
    Don't forget to comment, like and subscribe :)
    Social Media:
    Follow me on GitHub: bit.ly/ChapsasGitHub
    Follow me on Twitter: bit.ly/ChapsasTwitter
    Connect on LinkedIn: bit.ly/ChapsasLinkedIn
    Keep coding merch: keepcoding.shop
    #csharp #dotnet

Komentáře • 470

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

    Clean code doesn't equate to short code.

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

      If else if else doesn't equate

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

      One persons clean code is another persons absolute mess.

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

      @@mirabilis One person’s clean code is the rest of the worlds rat infested condemned building code…

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

      With all due respect kid. I'm a senior clean code developer. Where i'm going I don't need lines of code, I write it all on one line. You see those 12 layers of abstraction? That is what we call clever code. It means you literally can't phantom the level of perfection.

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

      @@TheCameltotem True, your saving storage space for the source too without all that extra white space.

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

    I personally have come to love switch expressions over the past year or so. Nesting ternary operators almost always leads to code that is hard to read.

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

      unfortunately nested ternary operators is the only way to describe conditional logic in expressions

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

      Same. I use both.

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

      *always. It always leads to code that is hard to read.

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

      Switch is good BUT it cannot handle cases where you want to compare case insensitive or with culture.

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

      @@nanvladOk, but even then some line-breaks would be handy to at least reflect the structure of the condition. That would help understanding what's going on there ...
      or maybe one could break the condition up into descriptively-named methods, if that makes sense in the particular case.

  • @bob-xm7ny
    @bob-xm7ny Před 8 měsíci +46

    The Art of software development is writing code humans can understand.

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

      So you’ll cater to the lowest common denominator…

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

      End user: am i a joke to you?

    • @bob-xm7ny
      @bob-xm7ny Před 7 měsíci

      @@bkcy18 it feels like you want me to say no... but....

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

      @@bkcy18 constantly to some people.

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

    Ternaries are nice when you only have the if option and the else option, even for somewhat complex things because multilining a single ternary is still readable. But nested ternaries are just universally bad.

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

      With the introduction of switch expressions I've practically stopped using ternaries. They're easier to adapt to changing criteria and generally speaking I think they're easier to read.

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

    That measuring tape has me cracking up 🤣

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

    Best use of ternary is in razor files, or string interpolation. However, once you start nesting, it's much cleaner to create a function

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

    My headcanon now includes Nick always carrying around a tape measure for code analysis.

    • @pw.70
      @pw.70 Před 8 měsíci

      I want a tape measure that can measure in characters too!!!

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

    I keep forgetting about the switch expression. It is very nice and concise. Thank you, Nick!

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

    I was of this opinion until yesterday while I was migrating a .NET 7 library to .NET Standard 2.0 (which unfortunately doesn't have switch expressions). In this situation, Rider actually did recommend a ternary operator refactor and the key to making it readable is the line breaks. The original example is perfectly fine with correctly placed line breaks:
    configSettings.DevelopmentEnvironment =
    environment is "UAT" ? "UAT" :
    environment is "PREPROD" ? "PRP" :
    environment is "PROD" ? "PRD" :
    string.Empty;
    In my opinion, this comes 2nd place in readability to the switch expression. In fact, it is very similar syntactically to the switch expression. If I was working with an older C# language version, I would use this.

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

      That is actually pretty easy to read, and its close to the switch expression

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

      With line breaks it has a little more sense

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

      Hello.
      I’m just wondering if there is some kind of blocker to prevent the LangVersion increase from being used in library?
      Since on LangVersion 11 the switch expression in netstandard2.0 definitely works.

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

      When you're following the rule to place operator on beginning of the next line, it looks more like this:
      configSettings.DevelopmentEnvironment = environment is "UAT"
      ? "UAT"
      : environment is "PREPROD"
      ? "PRP"
      : environment is "PROD"
      ? "PRD"
      : string.Empty;
      This way you know how ugly chaining ternary operators really is.

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

      @@magz198 Wondering this too because from my experience c#11 works almost completely fine on netstandard2.0.

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

    For a single if/else with assignment, I'd probably use the ternary operator. But in this case with else ifs, it's way too bad to read. I completely agree with using the switch expression here. It's the easiest to read of all of those ways and it's much cleaner imo.

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

      If the expression whose condition is being evaluated is short enough for a ternary, I typically opt for explicit one-line conditions, as you can maintain the brevity of a ternary but with a visually explicit semantic meaning.
      For example:
      if(condition) runFunction();
      else if(condition) runOtherFunction();
      It may look a bit odd seeing an if/else without opening a block for each condition, but I always prefer code to read like a sentence over syntactically shorter code with less explicit semantic meaning.
      Another such example to highlight what I mean is declaring an async function versus an async function expression. Which of these has a more immediately available semantic meaning:
      const readFile = async () => { … };
      async function readFile() { … };
      In the second example, the semantics are made available in the first two words and reads more naturally like an English sentence.
      I’m a relatively newer programmer, so I’d love to hear folks’ thoughts on this.

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

      I agree for short statements ternary operator is readable The biggest issue I have with the original code example is using IS for string comparisons, my second biggest issue is not having brackets, in my opinion all code should always have brackets and brackets start and end brackets should be on separate lines from other code, helps with readability knowing where start and end is, if the method/function is too large a comment should indicate what start the end goes with, but if your methods are that large you probably have code smells and need to refactored down to smaller chunks anyways.

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

      I find that multi-line ternaries are actually more readable than switch expressions. It's really the long single line ternaries that are unreadable.

  • @Andrei-cv5xt
    @Andrei-cv5xt Před 8 měsíci +10

    Just want to note that when you use dictionary of strings for mapping purposes then it's nice to specify string comparator for it. E.g. StringComparer.OrdinalIgnoreCase. Otherwise you might have issues in some scenarios. People forget this too often

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

    Ternary operators seem to be something new programmers latch onto. About 20 years ago, as a senior mentoring a junior, I saw he'd produced a piece of code that had *19* chained ternary calls. We had a conversation very much like this the one in this video. :)
    Computers will parse anything you throw at them; write code for humans, not for computers.

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

    "it's kinda long" with the measuring tape. I lost it. Beautifully executed.

  • @ayalamac
    @ayalamac Před 7 měsíci +2

    Hey Nick, I really appreciate the content you share. Here are my thoughts about this topic:
    Opting out of using 'else' or 'else if' in our code is an interesting practice that's quite different from replacing these with ternary operators. While a clean, single ternary operator can sometimes offer a neat solution, I believe that nesting them is universally frowned upon due to the complexity and readability issues it introduces.
    In my experience, adhering to the single responsibility principle often eliminates the need for additional conditional branching. This not only simplifies our code but also enhances its readability and maintainability. Good judgment and a clear understanding of the problem at hand can guide us to better coding practices without over-relying on ternary operators or excessive branching.
    Thanks for sparking this conversation, Nick. It's through discussions like these that we can share insights and continue to refine our coding techniques.
    Looking forward to more of your videos!

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

    I just learned about the switch expression a few days ago, and it's such a good addition to c#.

    • @0LoneTech
      @0LoneTech Před 7 měsíci

      Addition being a key word. While the formatting was terrible in the code example, before C# 8 (2019) switch expressions weren't available, and they didn't get combined patterns until C# 9 (2020). The ternary chain did make clearer that there was one specific assignment being made, but it should definitely have had each case on its own line and the Dictionary approach was better.

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

    Three seconds after seeing the if else if block, I said aloud, “Switch expression….”
    That ternary operator stuff just boggles the mind on how someone would prefer that, especially if you need to add more cases to evaluate to it.

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

    Omg switch expressions are such a breath of fresh air after so many years of "create hash map", "throw hash map at the problem".

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

    Oh wow! I haven't been following C# for a while, so haven't seen that switch expression, but it so nice how much the language design was pushed towards pattern matching for example. I have enjoyed writing C# before, but seems like I would have enjoyed even more now.

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

    Bruh, the measuring tape made my day. Thanks for awesome videos!

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

    Definitely use switch expression when that works. However, when the logic of the set of conditions varies (not just the value being compared) then I have used nested ternaries to good effect. However the rules are, only the else side may contain another ternary and the else ":" is always placed on a new line. Each line then is simply a condition and an outcome, its very readable yet compact. Oh and another rule is that the neither conditions nor the outcome value expressions should do any significant work.

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

    I'd use the ternary operator in such a way only if it's part of a method call with many parameters, and usually easy to understand. Something like this:
    Item item = new Item (a, b, c, d, e, f, g, h, i == true ? 1 : i == false ? 0 : -1, j, k, l, m);
    I don't want to use up ~5-10 lines solely for one parameter, especially if it's trivial logic.

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

    Switch Expression was the first thought when I saw the example. Love the feature.

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

      Yes. Please use it everybody.

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

      Mixed feelings; I agree but legacy code (old versions of c#) don't even support switch expressions...and one wouldn't be like telling their boss that they need to upgrade the version of c# in the code base so that they can use switch expression.
      BTW, my company's codebase is also on .NET Framework 4.7, thus upgrading our C# version would probably mean upgrading to .NET Core, which would entail a significant effort and/or risk.

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

    A big like for this video. I've seen a lot of senior devs' code where they just try to impress others with their knowledge of some C# feature but the code is barely readable and doesn't optimize anything.

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

    I've like to see the resulting IL code for these various options to see if there is any difference in the actual output of the compiler, or is it smart enough to recognize what we're trying to do and output essentially the same thing for all the versions. I'd bet they are all very similar with a bunch of string compares and jumps in series, except for the one using the dictionary.

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

      Compilers are very very smart these days.
      There is absolutely no point in torturing source code to make it “compact”. The compiler will undressed what is needed and produce optimal code.
      That’s if you have a compiler…

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

    Switch expression it's beautiful to cover such kind of code block. Thanks @Nick for making this video.

  • @user-tk2jy8xr8b
    @user-tk2jy8xr8b Před 8 měsíci +1

    > Stop Using if else if else In Your Code
    agree, don't use `else` at all, use early returns instead
    > use switch expr
    agree!
    > use ternary
    well sometimes it makes sense when multiple independent values have to be examined, but the format would be like this:
    var v = a
    ? b
    : c
    ? d
    : e
    ? f
    : g;
    but in general if it can be done without nesting ?:s - it should be done so.

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

    The switch expression is awesome!

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

    I would define those strings as constants as well, assuming they are going to be used in other places.

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

      Even private or local strings that are not going to change after being initialized are worth declaring as constants

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

      @@cruz1ale Hard disagree

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

      Or an enumeration

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

      Put Things in a constant as soon you are using it are more than one place thats my apprpoach

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

      @@xybersurfer I assume that not having constants makes code instantly readable. Having constant has advantage that it's impossible to make a typo or omit some while refactoring the code (such as renaming xml/json keys)

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

    I didn't know about switch expressions! That's really good to know!

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

    I like the use of the tape measure. Made me chuckle.

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

    I think this type of advice comes from an attempt to have as few new scopes and new lines as possible in your code because it can be confusing, and you'll have a method in which you have to scroll up and down to read.
    Now as Nick mentions, extracting a switch case and/or if-else statements into new methods is the best way. You'll get methods with few scopes and it will become a lot easier to read.
    Another rule of thumb that reinforces this is to check if the methods completely fit in your IDE, if it doesn't I generally tend to break it down into smaller methods.

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

      Except that the IDE size depends on your hardware. Silly suggestion tbh.

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

      That's true but the idea of a rule of thumb is to fit most situations not all of them...
      Most people use standard monitors with standard size and standard font size. Of course, there will always be a small percentage coding on a TV with font size 8 or less, but there's no way we can have a simple rule for junior devs if we try to account for all cases

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

    Totally agree. My first thought also was about using a switch.

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

    The closeup got me 🤣🤣

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

    Chained ternary operators is insane... and no Clean Code advocate would recommend that.

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

    I also like the solution where you create a function and just return a value from it, e.g.:
    ```
    if (env = "PROD")
    return "prd"
    If (env = "PREPROD")
    return "pprd"
    ...
    ```
    Although in this case when condition depends only on one variable, it makes much more sense to just use "switch" like you did.

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

    switch expression is an awesome feature. So easy to read.
    When things get bigger, the dictionary approach is the way to go IMO.

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

      I also like the dictionary approach. It’s more flexible in the long run.

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

    It looks like an advice from someone who just started their software development journey, when people come to the conclusion that fewer lines of code = better code. From my experience it comes from situations, where they are told to use a list instead of 20 variables and use a loop to go through them, because "it takes less lines of code"

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

      @@xybersurfer I think the problem is the "it takes less lines of code" not the using of the list over variables.

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

      ​@@xybersurfer yes, but the problem is when people take that simplified reasoning and apply it places that it is inappropriate.

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

    For this types of mappings i really like to use separate method looking like this:
    string Map(string param) => param switch
    {
    "Foo" => "Bar",
    _ => "Bazz"
    }
    Idk if it's clean approach but for me it's beautifull

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

    I can't believe people on linkedin looked at that post and genuinely said "yep, great advice 👍"

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

    I'm still new to switch expressions, but they're definitely better than nested ternary.
    Depending on how deep the switch options are, my usual preference is a function with a switch statement + early returns. That just makes the code using it cleaner to read and the switch can be tested separately.
    The dictionary is nice for dynamic data where the app using it isn't in control of how the data is produced.

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

    Agree, I have used nested ternary's before, but it was either poorly written code, or had some other reason (inlining something in Razor code in a Blazor project, in an elements property for example - You could make a method for it also, but sometimes its fine to use it in this situation)

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

    You can break the ternary operator into several lines, which makes it much clearer.
    But here I would also use a switch expression.

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

    I usually prefer switch expression for similar tasks, but this particular case now makes me wonder if it should be used with strings at all.
    Isn't pattern matching, used in switch expressions, basically a functional equivalent of pattern matching provided by 'is' keyword?
    To me it seems like we can't yet get the desired benefits of string.Equals while using switch expressions or 'is' keyword.
    (unless we abuse the 'when' keyword, but that's beyond the point)

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

    Depends on the context. In this example I would use a Swithc-statement, or a Dictionary.

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

    honestly thought this was going to be about polymorphism 😀. i agree with this video and my rule of thumb is ternary for single, simple conditions, otherwise switch or if/elses. it feels smart to chain ternaries, but they are unruly, hard to read, test, and modify.

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

    OMG my eyes hurt reading that! I guess some folks have never heard of the switch statement? This is another great example of ternary operator abuse.

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

    I know the "problem" here is the excess of "if else" statements. And as another clean code advice (which now I tend to think it's questionable too), I generally avoid else statements in my code. I even use continue, break and return to break the flow. But in this case, as you are dealing with strings, I tend to like the "if else" blocks, but I would change (as you told in your video) to string.Equals(..., ..., StringComparison."whatever is better for me"). This may look verbose, but it is still readable and with a reliable string comparison. The switch case is a great choice if you know exactly what you expect as the input. Finally, enclosing even one line of code inside the if statement is a better approach as it keeps visible what is going to be executed, even if the coder messes with the indentation. Great work on these series, Nick! Thanks to this now I won't follow blindly such questionable advices.

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

      Honest question:
      What is wrong with verbose? To me verbose means easy to read and understand. Not verbose means fewer key strokes. But then you have to put a lot more comments in the code to explain what everything does.
      Everyone has their own thing and lots of times coding practices are dictated by higher up. I get it. But I don't understand it.

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

    I was super worried about the message coming into this video but I agree 100%

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

    Thanks, you just introduced me to switch expressions.
    In C++, you wouldn't be able to use a switch on a string...except by hashing the strings into numbers by using a constexpr calculation (thus calculated at compile time).
    The risk being that if the hash can't be calculated at compile time you loose performance.

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

    Yeah no that’s crazy…
    If the code becomes too complex in the switch cases then a strategy pattern is also handy dandy 😊

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

    That must be a joke! Nested ternary operators are terrible!

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

      u didnt watch the whole vid

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

      Dicts and switch expressions is given in a video.

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

      You didn't understand my comment. I did watch the video and the switch expression was easy to read and elegant. I meant whoever suggested using nested ternary operators must have been trolling linked in or something as that's horrific to read!

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

    Wow that’s so much cleaner than the traditional switch case break default

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

    I would definitely also use a switch expression. Nice and clean. More videos like these.

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

    I just love this series ❤️

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

    100% agree with you. The only thing what comes to my mind when i see such advices: "Tell me you never worked in bigger teams on "real" production code, without telling me ...."

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

      Haha, if only that was true, this kind of bad use of ternary operator exists even in bigger team real production code. There are a lot of programmers out there poorly educated on how to write good code. Education seems to focus too much on the end results (i.e. working solution) over writing readable code.

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

      @@evancombs5159 Fair Point you are absolutly right. I think writing readable code is mostly experience. You have to read / refactor a lot of code (someone else or your own) to see what is readable and what is not.

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

    4:00 Almost spat my breakfast on my desk 🤣

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

    I believe the ternary operator advise might come from javascript where there's no switch expression, so you're forced to use if else, the ternary operator or the switch statement. With good formatting you might make the ternary operator resemble a switch expression.
    developmentEnvironment =
    environment === "UAT" ? "UAT"
    : environment === "PREPROD" ? "PRP"
    : environment === "PROD" ? "PRD"
    : "";
    Not that I recommend it, I've just seen it somewhere and it reminded me of that absurd advice from the video.

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

    Switch expressions FTW! I'm so glad that Java switch expressions:
    a. now exist since java 14, and
    b. now have pattern matching since java 21.

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

    switch expressions are GOAT

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

    var environment = "PREPROD";
    Func result = environment switch
    {
    "UAT" => () => "UAT",
    "PREPROD" => () => "PREPROD",
    "PROD" => () => "PROD",
    _ => () => string.Empty
    };
    Console.WriteLine(result());

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

    personally, if I see too many if/else statements that cannot be converted to switch, I just move them into a method, and do a short-circuit (if/return) it will make things much easier to follow, and reduce the levels of if/else statements to one level. but if it's possible, I would go with switch expression or a dictionary or Enum, whatever I see best fit for that code.

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

    On top of the explained mistakes , the post says that Ternary operator takes statements, in fact takes expressions

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

    first glance at the "clean line" => jaw drop!!!

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

    I like the pattern match switch expression. I also like chained ternary operators, but always on separate lines. Agree one long line is not good

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

    'It is kind of long!' Great moment in video! 😂 I like the dictionary, makes my libraries broadly compatible. So it is the best classical way...

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

    Wow, thank you. I never knew that C# has a postpositioned "switch" statement. Nice. 👍 Kinda reminds me, when I was in a project, we used functional programming in Java.

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

      Technically, the "switch" is in an infix position - between the expression to test and the block containing the branches.

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

    Wow I hade missed the switch expression. That looks really nice and easy to read.

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

    I agree, simplicity is always the better approach. Furthermore, being simple is one of the hardest tasks in software development. As an example, I've taken a long time to understand that I have to write code considering that other people will read my code. Thanks for your tips. It helps me a lot to keep this in mind.

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

      Definitely not always! Both these cases suck!
      The somewhat harder case but the best would’ve been making a configuration where you set then human readable name and the technical name as a pair for each environment. Read those in a hash and returned the key from the hash when they key is in the hash else return the default.
      Simplicity never brought us to the moon and back.

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

      It's important to mention that there is a big difference between being simple and being simplistic. Leonardo da Vinci once said, "Simplicity is the ultimate sophistication." IMHO, this emphasizes the value of simplicity in achieving elegance and sophistication. Albert Einstein emphasized the importance of simplicity when he said, "If you can't explain it to a six-year-old, you don't understand it yourself." The point is our simplicity is related to the audience that we are reaching. So, bearing this in mind, I guess that is always an opportunity to be simple.

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

      @@rodrigo_sparlock in that case I agree. And your last line is something that always rubs me the wrong way with clean code. As it targets the lowest common denominator.

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

    If I can, I try not to have else blocks in my code at all, but in situations where it's necessary, whether I use the ternary operator or not boils down to how simplistic the conditional logic is.
    The most complex ternary implementation I can justify using is something like "var result = flag ? ThisMethod() : ThatMethod();"
    Anything else, I would just suggest using if/else for readability or try to refactor our the else block if possible.

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

    The test for clean code is, as Robert C. Martin put it: Clean code leaves nowhere for bugs to hide. That, to me, is the complete definition. How easy is it to miss a bug in your code? Nested ternary operators combined with long variable names -- very easy, so it is _not_ clean code.

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

    A switch statement is case sensitive, a dictionary has a string comparison for the key on the constructor… a switch statement is great for enums and number types

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

    Hi Nick, I am have a problem with the ternary operator in C# Winforms, which appears to have some limitation in accepting this and asks (C# conditional expression is not valid in language version 7.3 upgrade to 9). Not sure how to handle this.

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

    I remember when I got my first developer job, and I started working on some legacy code over 10 years old. I frequently came across deeply nested ternaries and they were extremely hard to read and understand. Granted, I'd have an easier time now that I've been developing for a few years, but as a brand-new developer, nested ternaries are just dark magic.

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

    I would use the Dictionary before the switch expression became available in language. The larger switch statements become cumbersome quickly, and I find myself moving the content of them into separate methods anyways. With the fact that break is required for C# (Java, etc), the fall-through trick can't be leveraged anyways. Frankly, the expression was a long time coming. That said, I will use ternary expressions that are slightly lengthy as they are useful for assignments that have medium complexity, but I format the lines so that they are easier to read. if/else is usually still cleaner for more complicated logic (though usually those only occur for weird business rules or modifying smelly code that "there isn't enough time to refactor" or "too risky to refactor").

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

    I have a general rule of no nested ternary operators, mainly for readability.

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

    I prefer to create an enum type with a custom attribute which contains a string for the mapping "from" and "to" values. I'd have one method that translates the incoming string ("from" value) to the enum and another method that translates the enum to the outgoing string ("to" value). This is super convenient for both my library logic (using enums instead of strings) and I may have multiple "to"-like things that this enum value means in different contexts, so I'd have a different method for each mapping, all in one class for easy maintenance.

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

    Switch expressions are one of the very nice features in C#. Easy to understand and very clean.
    I think that some of these ppl that give “clean code” examples, don’t really use C#…

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

    if you put line breaks after colons on that long ternary it becomes perfectly readable, more than the IF else, and it is also shorter. But it requires a bit of tab formatting that people are not used to...

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

    in my opinion you should only use the ternary operator when you have a single if/else expression and it doesn't get too long. for this example i would always use a switch :DDD

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

    the ternary works well for 1 max 2 times and you can ident it better if 2. I usually prefer the else if as the other approches are bad when sudently your else now has to have 4 or 5 commands each. Also avoids the common mistake of forgetting a break in one of the cases and flow goes to the wrong case.

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

    When I read the title, I expected to get triggered, but instead you made me laugh, thanks :). I had no idea someone could come up with such a bad idea as nesting if-else-statements using ?:. A variant of Switch would definately be my go-to in this scenario, but if there were many alternatives I'd use a dictionary instead.

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

    I agree. Chaining the ternary op is SO hard to read.

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

      I never knew about switch expressions though! I only knew switch statements! This will DEF help me clean up my code!

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

    I like the switch expression.

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

    I read somewhere that using is for text isn't so bad (no pun intended), because the newer compiler figures is out in the background. No need for boxing aso. Ternary operator can be readable if you break it as you said on : but I always use switch if possible. Then you check the variable once, and evaluate many.

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

    It's hard to believe someone genuinely thought that was a good idea...

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

    I would like to see that example of "clean code" with let's say 20 conditions.

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

      I certainly wouldn’t use switch or if for that. A clear violation of the open closed principle. Use the strategy pattern instead. That way you only ever write new code and never modify existing code.

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

    Hi, Nick. I'm not a fan of the ternary operator for anything other than simple yes/no this/that decisions - like many on this thread, no doubt, the switch gets the vote.
    The best "switch" I've used over the years (pre-dating C# ) is the Pick Basic(*) "case" statement ...
    begin case
    case counter > 100
    //code
    case custId = ""
    //code
    case custId matches "4A3N"
    // code
    case (ordDate = today) or (ordDate = today-1)
    // code
    case 1
    // default
    end case
    Note the freedom to mix variable types - sooooo liberating. For all of C#'s smarts, I miss code like that. A lot. So READABLE. So MAINTAINABLE.
    [[(*) Dartmouth BASIC-like syntax, Pascal-like structure, C-like functions]]

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

    (1) Regarding string comparison, there is no difference between is and switch expression
    (2) Chained ternary operators were the only choice before switch expressions added to the language
    (3) Switch expressions are not supported yet in expression trees (for instance in LINQ for IQueryable), nor are if/then/else/switch statements, so chained ternary operators are still the only choice if you want to have similar translation expression inside query for e.g. EF Core that needs to be translatable to SQL
    (4) For normal programming nowadays of course switch expressions win

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

    Ternery chains can be very readable with appropriate new lines. I avoid even single ternery statements on one line, unless they're super short. But yes, switch statement is better when possible.

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

    I'll only use the ternary operator to replace a single if/else statement. More than than that I tend to go for a switch/case or a switch exression statement instead though I have used the Directory approach too. It depends really. but I would never ever used ternary in that way it's used here. Even if you break up the lines at the ? or : it would still be very hard to read.

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

    What? The advice is to have multiple ternary operations?! That's insane. My personal rule is to never use more than one ternary operation. And even then, I try to check if it looks good enough. When I see that someone did multiple ternary operations I get so annoyed, because why do I need to spend time to decode something that should be very simple?

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

    I love ternary operators, but only for one if else. Any more than that, I'd use a switch expression as well.

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

    I went 'oof' the moment you've shown it.

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

    This is always going to be relevant to the complexity of the conditions. For a large problem an interface, injection and concrete classes that take the values and then indicate the appropriate result. In this case, it is just big enough for a switch but too large for if-else. I did like the dictionary option for its simplicity and for simple large conditions it would be nice and fast. In summary, pick the right tools for the job.

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

    1000% Nick, they suggested it because they abolutely don't know about expressions like you suggest. I rarely see the need for a ternery except for the simple case of two items based on a simple boolean e.g. SomeFunction( isFirstTime ? "yes" : "no");

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

    If-else-if-else chain sometimes can be better than both switch or dictionary approaches. Because latter ones cannot correctly check incoming nullable value for null, but if-else can do it.
    And, in some cases, when incoming value is enum, sometimes new switch expression is unsafe when is missing default clause, so later this method can be broken when enum was expanded.
    In this cases, if-else chain and classic switch clause still can be more efficient.

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

    Uhhh no on using a ternary operation in this example. I would refactor it as you did... especially for maintainability.

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

    For those of us who are still forced to develop od .NET Framework 4.8...
    Personally I wouldn't change the if/else. It is very readable to me.
    If I'm using ternary op. and the lines are too long, I SPLIT IT with the operators on the start of the next line. e.g.
    var x = condition ? true : false;
    into
    var x =
    condition
    ? true
    : false;
    It is basically the if else by the number of lines, but that is more readable to me than long lines.
    In this case the logic would result into this:
    var developmentEnvironment =
    environment is "UAT"
    ? "UAT"
    : environment is "PREPROD"
    ? "PRP"
    : environment is "PROD"
    ? "PRD"
    : string.Empty;
    Which is less readable than those if/else, so I wouldn't use the ternary here.

  • @user-vu8fm5vb4n
    @user-vu8fm5vb4n Před 8 měsíci

    It all depends on context
    Sometimes if else chains makes the most sense, other times it could be switch, pattern matching or ternary operator
    Just.. if you ever need to write a 5000 characters long expression with ternary operators put some line breaks in there where it make sense, you're not writing minified js by hand

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

    Ternary is good in cases of "if not this, then that".
    Once you get further than that, especially for things that are obviously have the ability to grow overtime, I prefer the map option.