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

Поділитися
Вставка
  • Опубліковано 14 жов 2024
  • 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/nickwor...
    Don't forget to comment, like and subscribe :)
    Social Media:
    Follow me on GitHub: bit.ly/ChapsasG...
    Follow me on Twitter: bit.ly/ChapsasT...
    Connect on LinkedIn: bit.ly/ChapsasL...
    Keep coding merch: keepcoding.shop
    #csharp #dotnet

КОМЕНТАРІ • 468

  • @brianm1864
    @brianm1864 11 місяців тому +226

    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 11 місяців тому +4

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

    • @mirabilis
      @mirabilis 11 місяців тому

      Same. I use both.

    • @SkyyySi
      @SkyyySi 11 місяців тому +7

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

    • @davidmartensson273
      @davidmartensson273 11 місяців тому +1

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

    • @horse80hun
      @horse80hun 11 місяців тому +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.

  • @bloggrammer
    @bloggrammer 11 місяців тому +251

    Clean code doesn't equate to short code.

    • @gurumurthy6563
      @gurumurthy6563 11 місяців тому +2

      If else if else doesn't equate

    • @mirabilis
      @mirabilis 11 місяців тому +28

      One persons clean code is another persons absolute mess.

    • @NickSteffen
      @NickSteffen 11 місяців тому

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

    • @TheCameltotem
      @TheCameltotem 11 місяців тому +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 11 місяців тому +1

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

  • @cruz1ale
    @cruz1ale 11 місяців тому +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 11 місяців тому +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.

  • @bob-xm7ny
    @bob-xm7ny 11 місяців тому +51

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

    • @CallousCoder
      @CallousCoder 11 місяців тому +2

      So you’ll cater to the lowest common denominator…

    • @bkcy18
      @bkcy18 11 місяців тому +1

      End user: am i a joke to you?

    • @bob-xm7ny
      @bob-xm7ny 11 місяців тому

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

    • @KlebinDaBoca
      @KlebinDaBoca 10 місяців тому

      @@bkcy18 constantly to some people.

  • @AkariTheImmortal
    @AkariTheImmortal 11 місяців тому +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 11 місяців тому

      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 11 місяців тому

      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 11 місяців тому

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

  • @veec1539
    @veec1539 11 місяців тому +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

    • @DrHeinzDoofenshmirtz
      @DrHeinzDoofenshmirtz 11 місяців тому

      Or Excel

    • @katamas832
      @katamas832 11 місяців тому +1

      Or in return statements where you return this or that based on a logic value.

  • @jamesterwilliger3176
    @jamesterwilliger3176 11 місяців тому +51

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

    • @pw.70
      @pw.70 11 місяців тому

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

  • @DryBones111
    @DryBones111 11 місяців тому +33

    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 11 місяців тому

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

    • @emloq
      @emloq 11 місяців тому +1

      With line breaks it has a little more sense

    • @sinus3256
      @sinus3256 11 місяців тому +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 11 місяців тому

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

    • @olebogengthothela1191
      @olebogengthothela1191 11 місяців тому

      Nope. You didn't listen to Nick.

  • @onebike78
    @onebike78 11 місяців тому +15

    That measuring tape has me cracking up 🤣

  • @stephajn
    @stephajn 11 місяців тому +2

    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.

  • @Andrei-cv5xt
    @Andrei-cv5xt 11 місяців тому +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

  • @ayalamac
    @ayalamac 11 місяців тому +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!

  • @codingbloke
    @codingbloke 11 місяців тому +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 11 місяців тому +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.

  • @Sirozha1337
    @Sirozha1337 11 місяців тому

    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.

  • @Kestrel1971
    @Kestrel1971 10 місяців тому +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.

  • @WarrenGarabrandt
    @WarrenGarabrandt 11 місяців тому +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 11 місяців тому

      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…

  • @peterprins862
    @peterprins862 11 місяців тому +2

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

    • @0LoneTech
      @0LoneTech 11 місяців тому

      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.

  • @vonn9737
    @vonn9737 11 місяців тому +11

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

    • @cruz1ale
      @cruz1ale 11 місяців тому +6

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

    • @adambickford8720
      @adambickford8720 11 місяців тому +1

      @@cruz1ale Hard disagree

    • @garcipat
      @garcipat 11 місяців тому +2

      Or an enumeration

    • @pinguincoder
      @pinguincoder 11 місяців тому +1

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

    • @pavelperina7629
      @pavelperina7629 11 місяців тому

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

  • @LifeLoveAndMonads
    @LifeLoveAndMonads 11 місяців тому +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.

  • @StianHanger
    @StianHanger 11 місяців тому

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

  • @electrocatalyst
    @electrocatalyst 11 місяців тому

    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.

  • @ilyakurmaz
    @ilyakurmaz 11 місяців тому +3

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

    • @mirabilis
      @mirabilis 11 місяців тому

      Yes. Please use it everybody.

    • @brettr8263
      @brettr8263 11 місяців тому

      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.

  • @MyUbuntuVids
    @MyUbuntuVids 11 місяців тому +2

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

  • @jorgebranquinho8690
    @jorgebranquinho8690 11 місяців тому +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 11 місяців тому +1

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

    • @jorgebranquinho8690
      @jorgebranquinho8690 11 місяців тому

      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

  • @user-tk2jy8xr8b
    @user-tk2jy8xr8b 11 місяців тому +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.

  • @Majkelo879
    @Majkelo879 11 місяців тому

    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

  • @PPSzB
    @PPSzB 11 місяців тому +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 11 місяців тому

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

    • @evancombs5159
      @evancombs5159 11 місяців тому

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

  • @sealsharp
    @sealsharp 11 місяців тому +11

    The ternary can be more readable with linebreaks and indentation.
    The shown long line is fascinating to me. At some point, at last when scrolling and stitching together screenshots there had to be that "oh... Maybe this is stupid" moment.

    • @MaidenLoaf
      @MaidenLoaf 11 місяців тому +2

      Word. New line before the '?', true assignment on that line. New line before the ':', false assignment on that line. For quick conditional assignments it's nicer than the alternatives.

  • @Isr5d
    @Isr5d 11 місяців тому

    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.

  • @terjes64
    @terjes64 11 місяців тому

    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.

  • @stevenodlum4563
    @stevenodlum4563 11 місяців тому +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.

  • @freshairkaboom8171
    @freshairkaboom8171 10 місяців тому

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

  • @pretzel7g
    @pretzel7g 11 місяців тому +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.

  • @ErikBongers
    @ErikBongers 11 місяців тому

    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.

  • @BrunoDPO
    @BrunoDPO 11 місяців тому +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 11 місяців тому

      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.

  • @marioprieschl1782
    @marioprieschl1782 11 місяців тому +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 11 місяців тому

      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 11 місяців тому

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

  • @marsovac
    @marsovac 11 місяців тому

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

  • @youraveragedude8767
    @youraveragedude8767 11 місяців тому +4

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

  • @thiagomatu
    @thiagomatu 11 місяців тому +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 11 місяців тому

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

  • @그냥사람-e9f
    @그냥사람-e9f 11 місяців тому

    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

  • @paladine4life
    @paladine4life 11 місяців тому

    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.

  • @CRBarchager
    @CRBarchager 11 місяців тому +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.

  • @CubbyBear-cn5kh
    @CubbyBear-cn5kh 11 місяців тому

    I find I'll go for the double Ternaries, but once I hit the need for three, I'll go for a switch or just make a method with multiple ifs that return
    I do have lines of code like this:
    return string.IsNullorEmpty(value) ? "Error"
    : value.Length < 4 ? "Too Short"
    : value;
    but always multi line it.

  • @pedrosilva1437
    @pedrosilva1437 11 місяців тому +1

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

  • @bernardoherrera5217
    @bernardoherrera5217 11 місяців тому

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

  • @rodrigo_sparlock
    @rodrigo_sparlock 11 місяців тому

    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 11 місяців тому

      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 11 місяців тому +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 11 місяців тому +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.

  • @safyan_yaqoob
    @safyan_yaqoob 8 місяців тому

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

  • @justinian.erdmier
    @justinian.erdmier 11 місяців тому +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.

  • @petermiller3148
    @petermiller3148 11 місяців тому

    assuming they don't care about case, i would use
    var ic = StringComparison.InvariantCultureIgnoreCase;
    return environment switch
    {
    _ when environment.Equals("uat", ic) => "UAT",
    _ when environment.Equals("preprod", ic) => "PRP",
    _ when environment.Equals("prod", ic) => "PRD",
    _ => null
    };

  • @Galakyllz
    @Galakyllz 11 місяців тому +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.

  • @powermetal1963
    @powermetal1963 7 місяців тому

    (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

  • @redmasq
    @redmasq 11 місяців тому +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").

  • @Erlisch1337
    @Erlisch1337 11 місяців тому +1

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

  • @kvelez
    @kvelez 11 місяців тому

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

  • @rikschaaf
    @rikschaaf 11 місяців тому

    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.

  • @TheTigerus
    @TheTigerus 11 місяців тому +1

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

    • @leerothman2715
      @leerothman2715 11 місяців тому

      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.

  • @wknight8111
    @wknight8111 11 місяців тому

    I'm a person who believes in never using the else keyword. I have libraries with thousands of lines of code in them and not a single else (and, I believe, readability has improved because of it). But I also would never consider nesting ternary operators. Ternary operators by themselves can be difficult to read if done wrong, and nesting them just makes everything worse. In the example you showed with environment names I would probably use a switch expression, and in other places I would break out a separate method and use if/return instead of if/else.

  • @AbhinavKulshreshtha
    @AbhinavKulshreshtha 11 місяців тому +3

    I used multi-step ternary operator few months ago, mostly because in that perticular case, it looked much more elegant than elseif.
    But every ternary operation was on their own line, and properly indented . Never use long lines, no matter how wide screen you are using.

  • @Erik_The_Viking
    @Erik_The_Viking 11 місяців тому

    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.

  • @kirilldjakov8498
    @kirilldjakov8498 11 місяців тому

    switch expression is cool. One note on comparing strings: 'is' operator would act in the same way as switch expression. So, at least, use ToUpper()/(may be .Trim()) or the initial string

  • @andrewboyd6090
    @andrewboyd6090 11 місяців тому

    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

  • @sabinconstantinescu5355
    @sabinconstantinescu5355 11 місяців тому

    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#…

  • @b_roli_xd
    @b_roli_xd 11 місяців тому

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

  • @wagz2000
    @wagz2000 11 місяців тому +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.

  • @gregorymorse8423
    @gregorymorse8423 11 місяців тому +1

    Relying on maps isn't that great either. Try translating that to plain old C. Are you ready to deal with writing a bunch of functions to deal with the hash table memory management, a good universal hash function, etc? The most universal efficient and easy to implement method is likely a sorted list and binary search... which wasn't mentioned, at least unordered map is likely inferred though map was mentioned. Mainly the complexity of hash tables makes the efficiency not worth it except for performance critical places. However in languages like C# or Python then admittedly maps are relatively cheap. If wanting memory optimal code, then else if else if is the way to go. "Best coding practice" advice generally comes from those who never had to do size or space performance optimization. There is always an exception disclaimer for such critical areas of the code. The general advice is for non critical areas which in practice are the majority of cases. The ordered map variant is still quite a good tradeoff all around. In cases like this one, prefix comparisons and then one full comparison if found is going to get as fast as computing a hash and dealing with collisions. Hash tables do tend to waste memory without custom implementations. Though RAM is not generally an issue in most modern contexts.

  • @sm5574
    @sm5574 11 місяців тому

    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.

  • @CallousCoder
    @CallousCoder 11 місяців тому

    I have no problem reading ternary statements. But frankly I would’ve used a hash to translate thus, that I read from a configuration. Always extendable. And I avoid if then else in most cases. And switch is even worse in most languages with its indents and breaks - it’s nice here, in Zig and Rust.
    But the only good way here would be to have a configuration file with the human readable name and the technical name as key values. Read those into a hash and check the key exists return the value of that key else return the default name. That can be ternary. And this is always extensible and reusable for every other environment dependent code.

  • @gregorymeadows3572
    @gregorymeadows3572 11 місяців тому +1

    For `if/else` blocks that tend to do more work (more than just a map) I tend to refactor into a new method with early returns on the conditions etc. But I like the switch expressions for simple cases like this. much neater than `if/else` and wtf was that ternary operator? Were they high when they wrote it?
    I generally try and avoid the `else` keyword in general, as it can very quickly increase the cognitive load of a method or application.

  • @ps2goat297
    @ps2goat297 11 місяців тому

    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.

  • @northshorepx
    @northshorepx 11 місяців тому

    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 11 місяців тому

    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.

  • @elliott8596
    @elliott8596 11 місяців тому

    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.

  • @Sollace
    @Sollace 11 місяців тому

    2:13 If I were writing that specific example, the ternary operator _would_ be an option. I'd just just wrap it so it's not all on the same line.

  • @kevinison3740
    @kevinison3740 11 місяців тому +1

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

  • @SchnitzelMS
    @SchnitzelMS 11 місяців тому +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

  • @blacklotuslv
    @blacklotuslv 11 місяців тому

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

  • @jemakrol
    @jemakrol 11 місяців тому

    If else is often confused with ? : expression. Yes, you can mimic the behavior of ? : expression but they (in my opinion) have different use cases and if you don't understand them you'll end up with code lime the one shown.
    If else is governing control of flow. Which can include assignments. The only expression involved is really the condition that evaluates to boolean.
    ? : is an expression in itself, in the sense that it will evaluate to a result. It is clearly used in scenarios where you want fallbacks and similar more simple scenarios involving an assignment.
    As shown, ? : can be nested but I claim that the first step of cleaning up the mess in the example is simply by formatting it. Hear me out, I wouldn't settle for that but it would make that long line more readable. Much like you can make obfuscated if else readable by formatting.
    However, when you format nested ? : it will end up with a staircase. In comes switch expressions which is, as the name suggests, the solution to the problems with nested ? :

  • @lorcaranr
    @lorcaranr 11 місяців тому

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

  • @woocaschnowak
    @woocaschnowak 11 місяців тому +2

    I encounter PRs with nested ternaries from time to time in my job, and it's always a no-no for me. For me that's a code smell to say the least. I once saw some nesting that had conditions on both branches. Something along:
    var result = condition ?
    condition1 ?
    condition1_1 : value1_1_1 : value1_1_2
    condition1_2 : value1_2_1 : value1_2_2
    condition2 ?
    condition2_1 : value2_1_1 : value2_1_2
    condition2_2 : value2_2_1 : value2_2_2
    And I just can't understand how someone can think that's a proper solution to the problem...

    • @Zullfix
      @Zullfix 11 місяців тому +1

      I used to do this. Glad it didn't last long.

    • @woocaschnowak
      @woocaschnowak 11 місяців тому

      ​@@Zullfix this is in no way a hate speech, but do you remember, what was your reason to do it? I'm curious, because it may make it easier for me to explain to devs in my company why this isn't the way 🙂

    • @Zullfix
      @Zullfix 11 місяців тому +1

      @@woocaschnowak I would probably have to say because of laziness and a belief that less lines of code = better.
      I only ever use ternaries now when I am assigning a value to variables that will never need extra logic associated with it. For example, switching between 2 different string literals based on the count of a list, however let's say the list can also be null which has a third string literal associated with it. This now has 3 cases that could be handled with nested ternaries, however a standard if-else on the null check is both much more readable and future proof if we decide to do add more logic for when it is null.
      Additionally, there are many ways of writing a ternary expression on multiple lines, and depending on how it is done it can make it harder to follow logic flow or lead to bugs from a misplaced `:` or `?`. I know youtube comments aren't great for coding, but your nested ternary example won't compile because of some missing `:`s.
      Ternaries are great, but just because they're there doesn't mean they need to be used in every possible scenario in an effort to reduce line count. You're trying to write nice, easily readable code, not cram as much information into a paragraph as possible. I hate the new trend of "DX" this and "DX" that, but when comparing how fast you can mentally parse if (foo) { } else { } versus foo ? :, overuse of ternaries makes for a great example of negative developer experience.

  • @alexclark6777
    @alexclark6777 11 місяців тому

    My first thought was the switch expression as well, but the only downside (and there may be a workaround to this that I'm not aware of) is when you're trying to do a case-insensitive string comparison. If I was using .Equals(value, StringComparison.OrdinalIgnoreCase) then I don't think that allocates a new string, but with the switch expression the closest I can get is doing a switch on value.ToLower(), which still isn't quite the same as an ordinal ignore case comparison.
    The dictionary (or "map") approach here has the option to construct the dictionary object with a custom key comparer, so that would solve that issue. I wish there was a cleaner way to do the string comparison in the switch statement because IMO they make for some beautifully expressive code.

  • @duramirez
    @duramirez 11 місяців тому

    I use ternary only if I am initializing an object and I need to use an inline approach but even then, only if its short, otherwise I will store in a variable before and pass that along.

  • @JacobGlanz1234
    @JacobGlanz1234 11 місяців тому

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

  • @szymonsandura5882
    @szymonsandura5882 11 місяців тому +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)

  • @yeica
    @yeica 11 місяців тому

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

  • @davepusey
    @davepusey 11 місяців тому

    I didn't even think you could chain ternary operators like that. So yeah I would have 100% gone with a switch expression.

  • @killymxi
    @killymxi 11 місяців тому

    In the world before pattern matching, ternary chain looks kinda like it, _when appropriately formatted_ (one condition and true branch per line).
    No excuse to mimic switch expressions when they are available in the language.
    I remember writing such code in JS, because no switch _expressions_ there. I was struggling a bit without proper formatting support, because any auto-formatter tries to increase indentation at each line, as we would do when we have one condition or branch per line, and mimicking pattern matching is uncommon for anyone to care, unfortunately.
    When pattern matching will (hopefully) become reality there as well - there will be no need for this anymore.

  • @StarfoxHUN
    @StarfoxHUN 11 місяців тому

    Okay, i can't tell how annyoed i am for completely miss the existence of switch expressions...
    But anyways, i would not really say that it is a substitute to an if-else statement, as it might work in the provided example, but that is not always the case. That horrible '?' is able to replace an if-else anywhere, but switch only in certain situations.

  • @mheys1
    @mheys1 11 місяців тому +20

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

    • @Ripcraze
      @Ripcraze 11 місяців тому +2

      u didnt watch the whole vid

    • @blo0m1985
      @blo0m1985 11 місяців тому

      Dicts and switch expressions is given in a video.

    • @mheys1
      @mheys1 11 місяців тому

      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!

  • @miroslavmakhruk4102
    @miroslavmakhruk4102 11 місяців тому

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

  • @SecondFinale
    @SecondFinale 11 місяців тому

    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.

  • @mrwatkin
    @mrwatkin 11 місяців тому

    The dictionary use is a "Tell. Don't ask" approach. This can be done with Funcs as the values to invoke behavior as well.

  • @DaneWithADrone
    @DaneWithADrone 11 місяців тому

    For me, I would only use the ternary for simple, short and clear if..else statements, else I would use the switch. Never cascade the ternary! Its way more expressive to use switch for larger if/then/else as it lists in a clear way the different paths your code can take.

  • @davidhuber6319
    @davidhuber6319 11 місяців тому

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

  • @nanvlad
    @nanvlad 11 місяців тому

    Ok, Nick, I agree that one-liner nested ternary operators is a bad code, however multi-line ternary operators is the only way to describe conditional logic in translatable expression trees like in Mapster, EF Core etc. Expression trees don't support if/else, switch, ?? operators so the ternary operator is inevitable for such cases. Maybe Microsoft will allow at least 'switch' translation for expressions, but currently we don't have any other choice.

  • @Ashalmawia
    @Ashalmawia 11 місяців тому

    you can chain ternary and keep it readable as long as you use good indenting/whitespace. in this case switch expression is probably way better, yes, though it might not always work out that way. regardless of these examples, though, this kind of thing is very often a code smell, even as a switch expression. theoretically, since I don't know the actual code here, it should/could be pushed to some kind of meaningful type and these value pairs should be two properties on that type. then, if you have the need to look one up by one of those properties, they should be stored in a dictionary somewhere by that property. the main reason for this is that you should not have to know about and modify places in the code like this that perform such a mapping in an arbitrary place. there should be an obvious named canonical place for this mapping to live and it should be a place where other logic related to these values can live as well.

  • @kurisutofusan
    @kurisutofusan 11 місяців тому

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

  • @HelgiSkaft
    @HelgiSkaft 11 місяців тому

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

  • @rogerflatt8054
    @rogerflatt8054 11 місяців тому

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

  • @zethoun
    @zethoun 11 місяців тому

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