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 Жыл бұрын
unfortunately nested ternary operators is the only way to describe conditional logic in expressions
@mirabilis Жыл бұрын
Same. I use both.
@SkyyySi Жыл бұрын
*always. It always leads to code that is hard to read.
@davidmartensson273 Жыл бұрын
Switch is good BUT it cannot handle cases where you want to compare case insensitive or with culture.
@horse80hun Жыл бұрын
@@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 Жыл бұрын
Clean code doesn't equate to short code.
@gurumurthy6563 Жыл бұрын
If else if else doesn't equate
@mirabilis Жыл бұрын
One persons clean code is another persons absolute mess.
@NickSteffen Жыл бұрын
@@mirabilis One person’s clean code is the rest of the worlds rat infested condemned building code…
@TheCameltotem Жыл бұрын
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 Жыл бұрын
@@TheCameltotem True, your saving storage space for the source too without all that extra white space.
@cruz1ale Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
The Art of software development is writing code humans can understand.
@CallousCoder Жыл бұрын
So you’ll cater to the lowest common denominator…
@bkcy18 Жыл бұрын
End user: am i a joke to you?
@bob-xm7ny Жыл бұрын
@@bkcy18 it feels like you want me to say no... but....
@KlebinDaBoca Жыл бұрын
@@bkcy18 constantly to some people.
@veec1539 Жыл бұрын
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 Жыл бұрын
Or Excel
@katamas832 Жыл бұрын
Or in return statements where you return this or that based on a logic value.
@ayalamac Жыл бұрын
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!
@stephajn Жыл бұрын
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.
@onebike78 Жыл бұрын
That measuring tape has me cracking up 🤣
@jamesterwilliger3176 Жыл бұрын
My headcanon now includes Nick always carrying around a tape measure for code analysis.
@pw.70 Жыл бұрын
I want a tape measure that can measure in characters too!!!
@Andrei-cv5xt Жыл бұрын
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
@AkariTheImmortal Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
I find that multi-line ternaries are actually more readable than switch expressions. It's really the long single line ternaries that are unreadable.
@DryBones111 Жыл бұрын
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 Жыл бұрын
That is actually pretty easy to read, and its close to the switch expression
@emloq Жыл бұрын
With line breaks it has a little more sense
@sinus3256 Жыл бұрын
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 Жыл бұрын
@@magz198 Wondering this too because from my experience c#11 works almost completely fine on netstandard2.0.
@olebogengthothela1191 Жыл бұрын
Nope. You didn't listen to Nick.
@brianviktor8212 Жыл бұрын
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.
@codingbloke Жыл бұрын
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.
@Kestrel1971 Жыл бұрын
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.
@MyUbuntuVids Жыл бұрын
I keep forgetting about the switch expression. It is very nice and concise. Thank you, Nick!
@WarrenGarabrandt Жыл бұрын
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 Жыл бұрын
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…
@StianHanger Жыл бұрын
"it's kinda long" with the measuring tape. I lost it. Beautifully executed.
@peterprins862 Жыл бұрын
I just learned about the switch expression a few days ago, and it's such a good addition to c#.
@0LoneTech Жыл бұрын
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.
@LifeLoveAndMonads Жыл бұрын
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.
@Sirozha1337 Жыл бұрын
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.
@freshairkaboom8171 Жыл бұрын
Omg switch expressions are such a breath of fresh air after so many years of "create hash map", "throw hash map at the problem".
@vonn9737 Жыл бұрын
I would define those strings as constants as well, assuming they are going to be used in other places.
@cruz1ale Жыл бұрын
Even private or local strings that are not going to change after being initialized are worth declaring as constants
@adambickford8720 Жыл бұрын
@@cruz1ale Hard disagree
@garcipat Жыл бұрын
Or an enumeration
@WarpingWombat Жыл бұрын
Put Things in a constant as soon you are using it are more than one place thats my apprpoach
@pavelperina7629 Жыл бұрын
@@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)
@user-tk2jy8xr8b Жыл бұрын
> 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.
@PPSzB Жыл бұрын
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 Жыл бұрын
@@xybersurfer I think the problem is the "it takes less lines of code" not the using of the list over variables.
@evancombs5159 Жыл бұрын
@@xybersurfer yes, but the problem is when people take that simplified reasoning and apply it places that it is inappropriate.
@ilyakurmaz Жыл бұрын
Switch Expression was the first thought when I saw the example. Love the feature.
@mirabilis Жыл бұрын
Yes. Please use it everybody.
@brettr8263 Жыл бұрын
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 Жыл бұрын
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.
@jorgebranquinho8690 Жыл бұрын
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 Жыл бұрын
Except that the IDE size depends on your hardware. Silly suggestion tbh.
@jorgebranquinho8690 Жыл бұрын
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
@stevenodlum4563 Жыл бұрын
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.
@Majkelo879 Жыл бұрын
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
@pedrosilva1437 Жыл бұрын
Chained ternary operators is insane... and no Clean Code advocate would recommend that.
@CRBarchager Жыл бұрын
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.
@BrunoDPO Жыл бұрын
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 Жыл бұрын
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.
@gregorymeadows3572 Жыл бұрын
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.
@gregorymorse8423 Жыл бұрын
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.
@szymonsandura5882 Жыл бұрын
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)
@blacklotuslv Жыл бұрын
Bruh, the measuring tape made my day. Thanks for awesome videos!
@TheTigerus Жыл бұрын
I would like to see that example of "clean code" with let's say 20 conditions.
@leerothman2715 Жыл бұрын
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.
@safyan_yaqoob11 ай бұрын
Switch expression it's beautiful to cover such kind of code block. Thanks @Nick for making this video.
@terjes64 Жыл бұрын
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.
@thiagomatu Жыл бұрын
switch expression is an awesome feature. So easy to read. When things get bigger, the dictionary approach is the way to go IMO.
@TehKarmalizer Жыл бұрын
I also like the dictionary approach. It’s more flexible in the long run.
@marioprieschl1782 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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.
@pretzel7g Жыл бұрын
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.
@Isr5d Жыл бұрын
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.
@rodrigo_sparlock Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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.
@marsovac Жыл бұрын
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...
@ErikBongers Жыл бұрын
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.
@mirabilis Жыл бұрын
*lose
@Galakyllz Жыл бұрын
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 Жыл бұрын
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#…
@kevinison3740 Жыл бұрын
Uhhh no on using a ternary operation in this example. I would refactor it as you did... especially for maintainability.
@b_roli_xd Жыл бұрын
I can't believe people on linkedin looked at that post and genuinely said "yep, great advice 👍"
@redmasq Жыл бұрын
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").
@mheys1 Жыл бұрын
That must be a joke! Nested ternary operators are terrible!
@Ripcraze Жыл бұрын
u didnt watch the whole vid
@blo0m1985 Жыл бұрын
Dicts and switch expressions is given in a video.
@mheys1 Жыл бұрын
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!
@youraveragedude8767 Жыл бұрын
Yeah no that’s crazy… If the code becomes too complex in the switch cases then a strategy pattern is also handy dandy 😊
@CubbyBear-cn5kh Жыл бұрын
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.
@justinian.erdmier Жыл бұрын
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.
@Sollace Жыл бұрын
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.
@paladine4life Жыл бұрын
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.
@aj.arunkumar Жыл бұрын
i think people who doesnt know the difference between a statement and expression are the ones who falls for this bad "clean" code tip. i ve seen this in my project lot of times
@Erlisch1337 Жыл бұрын
Depends on the context. In this example I would use a Swithc-statement, or a Dictionary.
@ps2goat297 Жыл бұрын
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.
@razisraeli11502 ай бұрын
I just love your videos and tips!! ❤ keep it up, and thank you for the precious content Nick!
@wagz2000 Жыл бұрын
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.
On top of the explained mistakes , the post says that Ternary operator takes statements, in fact takes expressions
@andrewboyd6090 Жыл бұрын
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
@anvu6359 Жыл бұрын
At 2:37, can someone help me to understand why comparing string using the "is" operator is unsafe?
@alexwerf6084 Жыл бұрын
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.
@sacchin8535 Жыл бұрын
4:00 Almost spat my breakfast on my desk 🤣
@kurisutofusan Жыл бұрын
I didn't know about switch expressions! That's really good to know!
@Erik_The_Viking Жыл бұрын
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.
@rikschaaf Жыл бұрын
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.
@그냥사람-e9f Жыл бұрын
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
@syriuszb8611 Жыл бұрын
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?
@kirilldjakov8498 Жыл бұрын
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
@Palladin007 Жыл бұрын
You can break the ternary operator into several lines, which makes it much clearer. But here I would also use a switch expression.
@JacobGlanz1234 Жыл бұрын
Wow that’s so much cleaner than the traditional switch case break default
@woocaschnowak Жыл бұрын
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 Жыл бұрын
I used to do this. Glad it didn't last long.
@woocaschnowak Жыл бұрын
@@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 Жыл бұрын
@@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.
@duramirez Жыл бұрын
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.
@pingu2k4 Жыл бұрын
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)
@wknight8111 Жыл бұрын
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.
@sm5574 Жыл бұрын
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.
@northshorepx Жыл бұрын
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");
@SecondFinale Жыл бұрын
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.
@yeica Жыл бұрын
It's hard to believe someone genuinely thought that was a good idea...
@angrybob3594 Жыл бұрын
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.
@zethoun Жыл бұрын
first glance at the "clean line" => jaw drop!!!
@ChrisWard747 ай бұрын
With the use of the switch, is there a way to use a proper string comparison there right now if the environment was set to "prod" instead of "PROD" it wouldn't match.
@elliott8596 Жыл бұрын
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.
@davidhuber6319 Жыл бұрын
I was super worried about the message coming into this video but I agree 100%
@lorcaranr Жыл бұрын
I have a general rule of no nested ternary operators, mainly for readability.
@DerRobert28 Жыл бұрын
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 Жыл бұрын
Technically, the "switch" is in an infix position - between the expression to test and the block containing the branches.
@SchnitzelMS Жыл бұрын
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
@rogerflatt8054 Жыл бұрын
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]]
@davepusey Жыл бұрын
I didn't even think you could chain ternary operators like that. So yeah I would have 100% gone with a switch expression.
@kiwiproductions4510 Жыл бұрын
I like the use of the tape measure. Made me chuckle.
@javierolazaran7227 Жыл бұрын
The guy probably bought an ultra-wide screen and want to squeeze the juice out of it.
@alexclark6777 Жыл бұрын
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.
@arnewestedt1163 Жыл бұрын
Does the ternary operator have performance benefits ? Generally readability is preferred (not ternary in this case) unless performance is better no?
@Reellron Жыл бұрын
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.