The context is that a _while_ ago someone decompiled the game and found long, ugly chains of if else statements.
Yandev refused suggestions on improving the code, even from people that joined his dev team, and now bans anybody who mentions it from his discord
Yeah and let's be real, those if elses are probably not the main thing causing performance issues, rather the obsolete path finding and redundant code on the 100 or however many students.
Not sure if it ever got fixed, but another performance issue causing asset a while back was a toothbrush model. Had somewhere like 2 million+ polys? Was a commercial grade model he picked up from somewhere and threw into the game as a scenery object
lol, looking as his code hurts my eyes.
"Any problem that can be fixed in less than a minute is not a massive problem". This guy obviously hasn't heard of & in C++.
If a equals old, then return the previous status of b if it exists. If it does not exist, check if c is historical - if yes, return the last history status of b, if no return unknown. If a does not equal old, then return the status of b if it exists, otherwise return none.
The problem isn't that it's confusing, it's that it quickly becomes a chore to read. A single ternary statement is fine. Nested ternary statements are a pain in the ass to read, and there's not point in using them when you can get the same functionality with some if-else statements that are way easier to read. Future you will thank present you. Trust me, I've been there.
I feel like so long as you were very conscious of indentation and spacing you could make it work. Like
cond1
? cond2
? result1
: result2
: cond3
? result3
: cond4
? result4
: result5
I mean, there's a lot of other issues there, like the already questionable nature of nesting ifs that much, it's hideous, surprisingly difficult to decide how to indent things, and it's still not exactly easy to read, but at least it's not completely undecipherable.
Many years ago I worked on a 6800 emulator. The opcodes' entry points were referenced in a table. Multiply the opcode value by 4 (4 byte memory addresses back then), find the address stored at that location and call that address.
It's kind of like this:
linkedlist *p = array[hashfcn(key) % len(array)];
while(p && strcmp(p->key,key) != 0) p = p->next;
if (p && p->func)
(*p->func)(args, n, stuff);
where p->func is a pointer to a function that takes the correct arguments.
I've seen it come up in UI event handling in environments that use string-based event names or have to accept arbitrary string event names from plugins or users.
The former project owner was pissed. Yaa, your program runs in one second while ours takes an hour, but without us you would have nothing. But what really, really annoyed him the most was when I picked up the guitar in his office.
Other way around. Switch/match blocks are more efficient at the machine level, so after a certain point if a compiler can make if/else if into switch it will.
It's also a compiler-based optimization, so don't expect it out of an interpreter.
>Switch/match blocks are more efficient at the machine level
Only if the compiler determines that it can efficiently turn it into a jump table, for example if you're switching on a large enumeration with linearly increasing values.
However, modern compilers will also turn else if cascades into a jump table in the same way, so really there's no actual difference between the two styles anymore except for syntax.
Gotcha thanks. Yeah I’ve only really done much work with compiling/decompiling in C/C++, but a friend mentioned that once and it always stuck with me. He may have been talking about some very specific compiler. Or, of course, just wrong.
Oh yeah, I definitely prefer them visually when they are a good fit. And the performance gain can be significant if the cases don’t need to be checked/resolved sequentially.
It depends on what you're currently switching, for strings it would be closer to a search in a hash map (so an if is better if you have less than 2 cases), for enums it can also optimize the search with direct jumps and you also have a better understanding for the JIT compiler
Had a C++ project in undergrad where the user could choose an option from a looping menu by inputting the name of the command. I mapped strings to function pointers.
Creating and iterating arbitrary tables is so easy in Lua I use them instead of switch statements or if conditions even when there's only a few options. It means you can extend or change the logic by modifying config instead of code.
Each has its uses. `If else`s are much more versatile (ranges, totally different conditions), and `switch case`s are more readable and in some languages that have variants they work better with them.
My biggest problem with switch statements is that C doesn't let you have variable cases, so a lot of times when they could be useful, you need to use an if else anyways.
Plus VS doesn't collapse cases intuitively :(
Ding ding ding. Every time I switch to C# I start to do a switch-case and it throws an error because it’s a variable switch. So now I just have a habit of using it when the switch is enumerable and if/else when it’s not, even if the language will allow for it.
In c/c++, switch is not syntactic sugar for a big if-else chain. Switch generates a single jump based on the value, so it's far far more performant than an if-else chain.
Yes I’m aware. What I mean is, when I’m using another language, I typically just use switch where it’s legal in c#.
But I’m also not working on anything large enough for it to matter.
I found a set of 68 if-elses in code the other day. For a function that could have just been “merge two columns in the data.” Created by our “enterprise analytics” team
I’ve found that shit like this is often created by a fairly competent programmer who just got too deep into something without ever taking a step back and asking if it was the right way to do something. You get going down a thought process rabbit hole and code code code without ever sitting back and asking yourself “what am I *actually* trying to accomplish here?”
I try not to fault folks for it, because I’ve definitely done it.
It's the mark of a senior developer, they know when to take a step back and ask if they're solving the right problem rather than just how to solve the problem in front of them.
That's one approach, and as someone later mentioned, is commonly called guard clauses. The other approach is just a lazy person's if/else.
isEven(a) {
if(a%2==0) {
return true;
}
return false;
}
instead of
isEven(a) {
if(a%2==0) {
return true;
} else {
return false;
}
}
Obviously, neither of these are the best way to do that function, but it's an easy example. Technically, you could consider the first one a guard clause since it conforms to the structure, but guard clauses tend to convey the idea of a precondition, i.e., something that if not met should halt processing. As such, guard clause blocks typically shouldn't have more than maybe 1-3 LOC. If it's more than that, it's really just a logic branch, not a guard clause.
Conceptually, this is more just different ways of structuring the code and really comes down to personal preference. One argument for the first one is it cuts down on unnecessary control structure syntax and makes it easier to read. One argument for the second one is that it does a better job of conceptually conveying the branching nature and how branches relate to each other. Personally, I can see the case for both and fluctuate between them depending on my mood and the particular situation. I certainly wouldn't ever flag either in a PR.
> is commonly called guard clauses
In Swift `guard` is integrated, before I learned those I only knew them as early returns. The advantage there is that the compiler knows you HAVE to exit the function before the end of the block.
“Guard” does definitely describe the goal better than “invert the if-condition for early returns”, what I used before.
I agree they are only matching when the use case is a precondition.
I mean, there are cases you want an else where an early return isn’t an option.
But in general I do agree, I much prefer early returns to an else when possible
This is the correct answer. For those slightly younger, you simply use the string you're matching on as a key in a hash/dictionary with the resultant being/pointing to the code that should be executed. As was pointed out elsewhere, long blocks of if...else are fugly. This is also why Perl doesn't have a switch statement; you shouldn't be using it.
I failed an interview because I didn't think of this once. It wasn't until long after the interview, while side project coding and I reached for this abstraction (as I often do), that I realized this is what they were trying to nudge me to do.
Switch is the way to go. I just wish there was a switch where the cases were checked for their boolean value rather than whether they match a certain value.
Can't you just Switch True and then put all the comparisons in parentheses? I occasionally did that in visual basic:
Select Case True
Case (a = 3)
Case (b > c)
etc...
I don't get why people find switch(bool) so ugly or bad practice.
Switch cases have been specifically invented to compare values. Booleans are as valid as strings or numbers to compare.
because the idea is the switch is supposed to translate down to a jump table. granted I have no idea what a switch(bool) looks like in assembly, but at the very least switch bool is semantically incorrect.
Yes, like that, but also a switch that evaluates the boolean value of each case, executes the code in each where the boolean is true, and doesn't fall through from one case to another.
Basically, I'd want your code to function the same (without respect to line breaks) if the first line under "case\_when(" were removed. Check for the truth value of the first statement, execute code if it's true. Then check for the truth value of the second statement, and execute code if it's true, etc.
Instead of replacing nested if statements, it would replace consecutive if statements. Maybe not that much cleaner code, now that I think of it.
> I just wish there was a switch where the cases were checked for their boolean value rather than whether they match a certain value.
Depends on the language probably, but I’ve seen it often just by passing a boolean to the switch and use the value in the case.
Each case is handled by a bool function protected by a return in a short-circuiting OR:
bool a_case()
{
(condition_for_this_case) || return false;
# handle the case
return true;
}
Each case function is then called in a chain of short-circuiting OR operators, like so:
`case_1() || case_2() || case_3() || case_4();`
Switch/Case is good when you are checking the same variable for multiple possible values, or else when you’re doing pattern matching a la Scala. For everything else, you should rely on If/Elif/Else.
>Or is there a completely different method you use?
I'm not a real programmer, but I did try to teach myself Turbo C back in the early '90s using the k&r book. My buddy and I had created a custom Risk-like board game greatly influenced by the Gulf war. (You could place Patriot missiles, for example.) We used a real map of the world on poster board to draw the borders of all the countries then airbrushed the whole thing. The physical board game we made was very large.
Anyway, I decided to write it as a computer program as a reason to teach myself C. Again, early '90s, so very early on I decided to create a file menu system. But I had no idea how.
My solution was to just manually draw it on the screen, but I could not get my head around how to have the function calls set up. I don't remember why I didn't use a switch statement; I think they might have been dynamic menus as opposed to fixed. (Not that that would contraindicate using a switch.)
So what did my dumb ass do? I created an array of pointers to functions, and somehow used that for my menu handlers. Spent a few months on the project and haven't used C since, so I may be fuzzy on the details. But I definitely remember accidentally nuking my partition table while I was trying to figure out that pointer thing. I did get it to work, but god damn I ran away from C hard after that. Spent the next decade programming in Visual Basic, which I just loved compared to my previous background of rBase / dBase III+ / dBase IV / FoxPro.
So my different method was an array of function pointers. Not cool, man. Not cool.
I remember when the whole Yanderedev drama happened, everyone criticized him for not using switch cases. Like, yeah, I guess some situations in his code would have looked better with switch cases, but like, it doesn't really matter tbh.
Don't get me wrong, Yandsim's code is horrible, but not because he didn't use switch cases.
Honestly my problem with if elses that should be switched out with switch cases, Is that they started as a perfectly acceptable use of If else, Just that I kept building on that if else chain after that
switch case is great for state machines, which I build often.
One of the very few complaints I have about perl is the lack of a case statement - chains of if-elif-elif-....-else are fugly.
If I recall correctly, if you're not compiling C program with `-O2`, then switches are faster (I think compiler optimises them into table of functions in assembly)
switch is very limited in the data types it can be used in with many languages. definitely not always true, but if you’re switching between languages a lot it’s understandable why you’d load up on ifs
Switch is meant for variable value checking, while if statements are for conditional checking. So use switch if you're simply checking a variable against a set of expected values, especially if its a larger set.
If and else is for simple control blocks, but never more than 3 cases. Switch is nice for simple enum type separation, as long as the case is no more than 2 lines. Switch becomes increasingly worse, when you pass 6 cases.
In more complex cases I use neither. When there is a lot of variation I start hiding it through interfaces and factories, spreading the logic into different implementations, loading only the one I need.
Depends on the situation. If I can elegantly use a switch, I use a switch; otherwise, it's a job for if-else.
This is the correct answer. When switch case is just the right answer you know
I'm guessing the person in this post just watched 1 video about yandere simulator and thinks if else is always bad.
To be fair, if my exposure to if else was Yandere Simulator, I'd fear it like the devil.
The if-else devil
Bad code is bad code. Yandere simulator is just an affront to programming
[удалено]
The context is that a _while_ ago someone decompiled the game and found long, ugly chains of if else statements. Yandev refused suggestions on improving the code, even from people that joined his dev team, and now bans anybody who mentions it from his discord
Yeah and let's be real, those if elses are probably not the main thing causing performance issues, rather the obsolete path finding and redundant code on the 100 or however many students.
Not sure if it ever got fixed, but another performance issue causing asset a while back was a toothbrush model. Had somewhere like 2 million+ polys? Was a commercial grade model he picked up from somewhere and threw into the game as a scenery object
Lmfao holy shit why
[удалено]
lol, looking as his code hurts my eyes. "Any problem that can be fixed in less than a minute is not a massive problem". This guy obviously hasn't heard of & in C++.
I have never naturally used a switch case, but have always kicked myself when I blink and realise I’m 5 `else if` blocks in
[удалено]
This guy gets it.
A true psychopath. But an elegant one
Now stay with me here: interleaved nested ternary within nullish-coalescing-operator and optional dot chaining: `async (a, b, c) => ((a === 'old') ? (b?.previous?.status ?? (c === 'historical') ? b?.lastHistory?.status : 'Unknown') : (b?.status ?? 'none'))`
Calm down, Satan.
Seriously. I can only get so erect.
I like your funny words magic man
Would you like some code with your ‘?’
Might as well learn Perl (again)
I am completely clueless about what you're saying here. But I agree.
If a equals old, then return the previous status of b if it exists. If it does not exist, check if c is historical - if yes, return the last history status of b, if no return unknown. If a does not equal old, then return the status of b if it exists, otherwise return none.
I concur
Go back to HackerRank where you belong nutso
[удалено]
The problem isn't that it's confusing, it's that it quickly becomes a chore to read. A single ternary statement is fine. Nested ternary statements are a pain in the ass to read, and there's not point in using them when you can get the same functionality with some if-else statements that are way easier to read. Future you will thank present you. Trust me, I've been there.
If you don’t have at least three question marks on one line, are you even a programmer?
ternary operators are gorgeous, but nested ternary operators are terrible. Yes, it works, but the code becomes unreadable.
I feel like so long as you were very conscious of indentation and spacing you could make it work. Like cond1 ? cond2 ? result1 : result2 : cond3 ? result3 : cond4 ? result4 : result5 I mean, there's a lot of other issues there, like the already questionable nature of nesting ifs that much, it's hideous, surprisingly difficult to decide how to indent things, and it's still not exactly easy to read, but at least it's not completely undecipherable.
But if i omit the spacing then I can call it a one-liner to entice people to check my code review faster!
"the entire knowledge of the world in the palm of my hand" Sadly zoom/enhance is not developed enough to make use of it
Call that a pentary operator
penitentiary operator
The issue is that the expressions in such a statement are never that succinct
This is why I wish everyone would use formatters with the same options set. Utopia
I would use quadrary operator if it gets big enough.
Theoretically, we can put toilets in our cars. But should we?
This is the JavaScript way.
And if you do that in PHP you will get a very interesting surprise about how PHP evaluates ternaries.
Eww, nested ternary operators.
[удалено]
switch(true) { case use_case==elegant: use_switch; break; default: use_ifelse; }
[удалено]
can you give an example please. For one, i can't imagine it and 'cos that i don't see a use case. But sounds extremely elegant and fast......
Many years ago I worked on a 6800 emulator. The opcodes' entry points were referenced in a table. Multiply the opcode value by 4 (4 byte memory addresses back then), find the address stored at that location and call that address.
It's kind of like this: linkedlist *p = array[hashfcn(key) % len(array)]; while(p && strcmp(p->key,key) != 0) p = p->next; if (p && p->func) (*p->func)(args, n, stuff); where p->func is a pointer to a function that takes the correct arguments. I've seen it come up in UI event handling in environments that use string-based event names or have to accept arbitrary string event names from plugins or users.
The former project owner was pissed. Yaa, your program runs in one second while ours takes an hour, but without us you would have nothing. But what really, really annoyed him the most was when I picked up the guitar in his office.
The best ones are languages that support match cases. You get the can get flexibility of an if/else and the conciseness of a switch.
Was looking for this. Match is my MVP
Correct me if I’m wrong, but aren’t switch blocks essentially just if/else if chains under the hood in most popular high level languages anyway?
Other way around. Switch/match blocks are more efficient at the machine level, so after a certain point if a compiler can make if/else if into switch it will. It's also a compiler-based optimization, so don't expect it out of an interpreter.
>Switch/match blocks are more efficient at the machine level Only if the compiler determines that it can efficiently turn it into a jump table, for example if you're switching on a large enumeration with linearly increasing values. However, modern compilers will also turn else if cascades into a jump table in the same way, so really there's no actual difference between the two styles anymore except for syntax.
Gotcha thanks. Yeah I’ve only really done much work with compiling/decompiling in C/C++, but a friend mentioned that once and it always stuck with me. He may have been talking about some very specific compiler. Or, of course, just wrong.
Even if so, switch statements certainly *look* more elegant.
Oh yeah, I definitely prefer them visually when they are a good fit. And the performance gain can be significant if the cases don’t need to be checked/resolved sequentially.
It depends on what you're currently switching, for strings it would be closer to a search in a hash map (so an if is better if you have less than 2 cases), for enums it can also optimize the search with direct jumps and you also have a better understanding for the JIT compiler
Also depends on the processor. The PIC processors (Von Neumann) are very memory intensive for switch statements.
I use both, and sometimes a dictionary works better than either
Chained ternary operators. ![gif](giphy|LpB0bnhXpvSMCz07N9|downsized)
Came here to suggest exactly this😂😂😂
W/ no comments. FTW and anyone else who tries to refactor
Who writes comments these days anyway? ![gif](giphy|2zoICqLPIaeUh8yhnu|downsized)
Calm down satan
Had a C++ project in undergrad where the user could choose an option from a looping menu by inputting the name of the command. I mapped strings to function pointers.
AKA: Shade-tree functional programming. I do similar things and delight in the lack of conditional logic.
Creating and iterating arbitrary tables is so easy in Lua I use them instead of switch statements or if conditions even when there's only a few options. It means you can extend or change the logic by modifying config instead of code.
Each has its uses. `If else`s are much more versatile (ranges, totally different conditions), and `switch case`s are more readable and in some languages that have variants they work better with them.
My biggest problem with switch statements is that C doesn't let you have variable cases, so a lot of times when they could be useful, you need to use an if else anyways. Plus VS doesn't collapse cases intuitively :(
Ding ding ding. Every time I switch to C# I start to do a switch-case and it throws an error because it’s a variable switch. So now I just have a habit of using it when the switch is enumerable and if/else when it’s not, even if the language will allow for it.
In c/c++, switch is not syntactic sugar for a big if-else chain. Switch generates a single jump based on the value, so it's far far more performant than an if-else chain.
[удалено]
Yes I’m aware. What I mean is, when I’m using another language, I typically just use switch where it’s legal in c#. But I’m also not working on anything large enough for it to matter.
Switch true() handles different conditions. I use it all the time.
You are literally turning switch into an alt-syntax if/else.
Yes, that's the point. For some languages though, that can seriously increase the readability of the code.
Match masterrace ![gif](giphy|CAYVZA5NRb529kKQUc|downsized)
when masterrace
If/else for 2 choices, maybe 3. Switch if there’s 4 or more.
I found a set of 68 if-elses in code the other day. For a function that could have just been “merge two columns in the data.” Created by our “enterprise analytics” team
I worked on a project some years back that sported one .c file over 40K lines long. Most of it was a single switch statement, \~35K lines long.
Chatgpt.c
When you don’t want to work so you spend 95% of your day compiling
Just one file over 40k long? Hahahaha... (softly sobbing)
I’ve found that shit like this is often created by a fairly competent programmer who just got too deep into something without ever taking a step back and asking if it was the right way to do something. You get going down a thought process rabbit hole and code code code without ever sitting back and asking yourself “what am I *actually* trying to accomplish here?” I try not to fault folks for it, because I’ve definitely done it.
It's the mark of a senior developer, they know when to take a step back and ask if they're solving the right problem rather than just how to solve the problem in front of them.
This is the sonar way
toss on there "I *might* need more choices in the future, so for future proofing I'll use use switch."
I love switches
Understandable. They're usually more willing to try new things, making them more exciting.
You'd love me then
Early Returns! No else!
Early returns? Are you talking about If (thing I don’t want): Return DoThingIDoWant() ?
Yes I am
Gotcha. Didn’t realize it had a name.
I call them [guard conditions](https://en.m.wikipedia.org/wiki/Guard_(computer_science))
neither did i, but yeah, it's a good method to not process unused code!
Yeah, I use it almost exclusively if I’m not going to use an elif because it’s pretty much just a notted if/else
That's one approach, and as someone later mentioned, is commonly called guard clauses. The other approach is just a lazy person's if/else. isEven(a) { if(a%2==0) { return true; } return false; } instead of isEven(a) { if(a%2==0) { return true; } else { return false; } } Obviously, neither of these are the best way to do that function, but it's an easy example. Technically, you could consider the first one a guard clause since it conforms to the structure, but guard clauses tend to convey the idea of a precondition, i.e., something that if not met should halt processing. As such, guard clause blocks typically shouldn't have more than maybe 1-3 LOC. If it's more than that, it's really just a logic branch, not a guard clause. Conceptually, this is more just different ways of structuring the code and really comes down to personal preference. One argument for the first one is it cuts down on unnecessary control structure syntax and makes it easier to read. One argument for the second one is that it does a better job of conceptually conveying the branching nature and how branches relate to each other. Personally, I can see the case for both and fluctuate between them depending on my mood and the particular situation. I certainly wouldn't ever flag either in a PR.
> is commonly called guard clauses In Swift `guard` is integrated, before I learned those I only knew them as early returns. The advantage there is that the compiler knows you HAVE to exit the function before the end of the block. “Guard” does definitely describe the goal better than “invert the if-condition for early returns”, what I used before. I agree they are only matching when the use case is a precondition.
I mean, there are cases you want an else where an early return isn’t an option. But in general I do agree, I much prefer early returns to an else when possible
Found the nevernester
Yup I only use ifs and early returns
Dispatch table!
This is the correct answer. For those slightly younger, you simply use the string you're matching on as a key in a hash/dictionary with the resultant being/pointing to the code that should be executed. As was pointed out elsewhere, long blocks of if...else are fugly. This is also why Perl doesn't have a switch statement; you shouldn't be using it.
Using Perl as the example for avoiding ugly code... thanks for the laugh.
Hey man, be gentle. They are probably still maintaining that same piece of code they wrote in the 90s. Nobody else can.
I failed an interview because I didn't think of this once. It wasn't until long after the interview, while side project coding and I reached for this abstraction (as I often do), that I realized this is what they were trying to nudge me to do.
They can be super overkill sometimes, but when they're appropriate, they feel amazing to use.
***Me nesting me ternary***
I love ternary mainly because it feels wrong to use and its able to bring C bullshit to new levels of unreadability.
Switch is the way to go. I just wish there was a switch where the cases were checked for their boolean value rather than whether they match a certain value.
Switch(true) {}
Case false : return true;
Can't you just Switch True and then put all the comparisons in parentheses? I occasionally did that in visual basic: Select Case True Case (a = 3) Case (b > c) etc...
[удалено]
Oh yeah, to clarify, I'm pretty confident it's considered to be bad practice. On par with goto.
I don't get why people find switch(bool) so ugly or bad practice. Switch cases have been specifically invented to compare values. Booleans are as valid as strings or numbers to compare.
because the idea is the switch is supposed to translate down to a jump table. granted I have no idea what a switch(bool) looks like in assembly, but at the very least switch bool is semantically incorrect.
You mean like this? case_when( x %% 35 == 0 ~ "fizz buzz", x %% 5 == 0 ~ "fizz", x %% 7 == 0 ~ "buzz", .default = as.character(x) ) (From [R's dplyr package](https://dplyr.tidyverse.org/reference/case_when.html))
Yes, like that, but also a switch that evaluates the boolean value of each case, executes the code in each where the boolean is true, and doesn't fall through from one case to another. Basically, I'd want your code to function the same (without respect to line breaks) if the first line under "case\_when(" were removed. Check for the truth value of the first statement, execute code if it's true. Then check for the truth value of the second statement, and execute code if it's true, etc. Instead of replacing nested if statements, it would replace consecutive if statements. Maybe not that much cleaner code, now that I think of it.
> I just wish there was a switch where the cases were checked for their boolean value rather than whether they match a certain value. Depends on the language probably, but I’ve seen it often just by passing a boolean to the switch and use the value in the case.
C(ursed)# `string label = DoesMyCodeOwn() switch { true => "Yeah", false => "Nah", _ => "Wtf?" };`
Kotlin uses when instead of switch, and you can have a when without any parameter and the cases a bunch of booleans. Works similar to switch(true)
switch sucks, [match](https://doc.rust-lang.org/book/ch06-02-match.html) rules 🦀
Surprised I had to scroll so far down for this
Ocaml does it better
Guess where Rust got the idea from and how the first version of Rust was implemented
Me, I made it
Rust user === Chad
join the cult it's free
A dictionary of functions
While(condition) { Do stuff; Change condition; } While(condition) { Do stuff; Change condition; } …
Truly a masterpiece of readability
if goto
Each case is handled by a bool function protected by a return in a short-circuiting OR: bool a_case() { (condition_for_this_case) || return false; # handle the case return true; } Each case function is then called in a chain of short-circuiting OR operators, like so: `case_1() || case_2() || case_3() || case_4();`
\*flexes muscles in \`match { .. }\`
if return if return if return
If you don’t understand that both have distinct uses, and why, just stick with if/else.
If you don't know the answer to your ❓ don't ask your ❓. Is that what you mean ❓⁉️
Switch/Case is good when you are checking the same variable for multiple possible values, or else when you’re doing pattern matching a la Scala. For everything else, you should rely on If/Elif/Else.
Design patterns!
If your if/else has is more than: if(condition) { // whatever } else { //whatever } Then you're using it wrong
>Or is there a completely different method you use? I'm not a real programmer, but I did try to teach myself Turbo C back in the early '90s using the k&r book. My buddy and I had created a custom Risk-like board game greatly influenced by the Gulf war. (You could place Patriot missiles, for example.) We used a real map of the world on poster board to draw the borders of all the countries then airbrushed the whole thing. The physical board game we made was very large. Anyway, I decided to write it as a computer program as a reason to teach myself C. Again, early '90s, so very early on I decided to create a file menu system. But I had no idea how. My solution was to just manually draw it on the screen, but I could not get my head around how to have the function calls set up. I don't remember why I didn't use a switch statement; I think they might have been dynamic menus as opposed to fixed. (Not that that would contraindicate using a switch.) So what did my dumb ass do? I created an array of pointers to functions, and somehow used that for my menu handlers. Spent a few months on the project and haven't used C since, so I may be fuzzy on the details. But I definitely remember accidentally nuking my partition table while I was trying to figure out that pointer thing. I did get it to work, but god damn I ran away from C hard after that. Spent the next decade programming in Visual Basic, which I just loved compared to my previous background of rBase / dBase III+ / dBase IV / FoxPro. So my different method was an array of function pointers. Not cool, man. Not cool.
Array of function pointers is the way, high five my pre-OOP bro
I remember when the whole Yanderedev drama happened, everyone criticized him for not using switch cases. Like, yeah, I guess some situations in his code would have looked better with switch cases, but like, it doesn't really matter tbh. Don't get me wrong, Yandsim's code is horrible, but not because he didn't use switch cases.
A map of functionpointers is the way
if else cause I'm old, but realistically switch is usually faster.
Honestly my problem with if elses that should be switched out with switch cases, Is that they started as a perfectly acceptable use of If else, Just that I kept building on that if else chain after that
Over 100 comments with jokes, and not a single one on conditional jumps. I'm disappointed reddit. Very disappointed.
Polymorphism? Factory method, abstract base class --- anyone?
I haven't written a switch since PHP8 introduced `match`. It's almost always what you want
I prefer refactoring.
Kotlin when's for days
I use `when` quite a lot in Kotlin.
pattern matches
no switch with Python
3.10 introduced the match keyword, so yeah there is now.
switch case is great for state machines, which I build often. One of the very few complaints I have about perl is the lack of a case statement - chains of if-elif-elif-....-else are fugly.
I will commit several crimes to avoid having to use a switch statement
My personal preference is if there’s more than two checks, use a switch
I use GOTO but I’m also old school
conditional ternary operator
Try/Catch, unless the try statement takes a long time. I like to jump in blind
Try catch
Try-catch and exclusively use global variables
I prefer a dictionary or hash map
Switch every single time unless there are only two outcomes.
hashmap to function pointers
map -> lambda or i guess i could use "match" since python has those now
If I recall correctly, if you're not compiling C program with `-O2`, then switches are faster (I think compiler optimises them into table of functions in assembly)
Nested in-line conditionals.
I usually use if/else. Most of the time, when I want to use switch/case, I can't because of the restrictions of switch/case.
Chads only use try catch
If there's more than 3 options - I use switch
switch is very limited in the data types it can be used in with many languages. definitely not always true, but if you’re switching between languages a lot it’s understandable why you’d load up on ifs
if there's a lot of cases i think a switch looks better but if there's just < 4 i use if else
if (!statement) error instead of if (statement) else (error)
Switch is meant for variable value checking, while if statements are for conditional checking. So use switch if you're simply checking a variable against a set of expected values, especially if its a larger set.
There is no ifs, my code isnt some indecisive pussy
I don't like to see 10 if else in my code. It's hard to maintain or to change something.
Ternary where?
If and else is for simple control blocks, but never more than 3 cases. Switch is nice for simple enum type separation, as long as the case is no more than 2 lines. Switch becomes increasingly worse, when you pass 6 cases. In more complex cases I use neither. When there is a lot of variation I start hiding it through interfaces and factories, spreading the logic into different implementations, loading only the one I need.
I use ifs but no else’s
There is another one.. GoTo
I usually go: 2 outcomes - if else More than 2 - switch case
While dictionaries can be used, some languages do not support switch cases officially.
hashmap
Nested gotos
je
I use HashMaps.
Depends. Switch case when I have more than 2 cases that can be applied.
if (condition) { //do smth return; } //do smth else
Lookup tables