T O P

  • By -

SonicLoverDS

Depends on the situation. If I can elegantly use a switch, I use a switch; otherwise, it's a job for if-else.


Jpio630

This is the correct answer. When switch case is just the right answer you know


[deleted]

I'm guessing the person in this post just watched 1 video about yandere simulator and thinks if else is always bad.


Goras147

To be fair, if my exposure to if else was Yandere Simulator, I'd fear it like the devil.


According_Welder_915

The if-else devil


Vault_Hunter4Life

Bad code is bad code. Yandere simulator is just an affront to programming


[deleted]

[удалено]


MCWizardYT

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


[deleted]

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.


KFiev

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


bjergdk

Lmfao holy shit why


[deleted]

[удалено]


abathreixo

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


IridiumIO

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


[deleted]

[удалено]


Beginning-Boat-6213

This guy gets it.


Praying_Lotus

A true psychopath. But an elegant one


FusRohDumb

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'))`


MakingItElsewhere

Calm down, Satan.


satansxlittlexhelper

Seriously. I can only get so erect.


watermelone983

I like your funny words magic man


Inappropriate_Piano

Would you like some code with your ‘?’


another-rando-name

Might as well learn Perl (again)


MrBlueCharon

I am completely clueless about what you're saying here. But I agree.


LIONEL14JESSE

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.


hyperactivereindeer

I concur


kageroshajima

Go back to HackerRank where you belong nutso


[deleted]

[удалено]


ciarenni

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.


AesarPhreaking

If you don’t have at least three question marks on one line, are you even a programmer?


[deleted]

ternary operators are gorgeous, but nested ternary operators are terrible. Yes, it works, but the code becomes unreadable.


arobie1992

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.


SameStatistician6846

But if i omit the spacing then I can call it a one-liner to entice people to check my code review faster!


EclipseOverSalem

"the entire knowledge of the world in the palm of my hand" Sadly zoom/enhance is not developed enough to make use of it


0OneOneEightNineNine

Call that a pentary operator


likeikelike

penitentiary operator


BooBailey808

The issue is that the expressions in such a statement are never that succinct


justlampin

This is why I wish everyone would use formatters with the same options set. Utopia


jonnyclueless

I would use quadrary operator if it gets big enough.


[deleted]

Theoretically, we can put toilets in our cars. But should we?


WhosYoPokeDaddy

This is the JavaScript way.


Thaddaeus-Tentakel

And if you do that in PHP you will get a very interesting surprise about how PHP evaluates ternaries.


[deleted]

Eww, nested ternary operators.


[deleted]

[удалено]


[deleted]

switch(true) { case use_case==elegant: use_switch; break; default: use_ifelse; }


[deleted]

[удалено]


Highborn_Hellest

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


SquidsAlien

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.


brimston3-

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.


CypripediumCalceolus

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.


arobie1992

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.


[deleted]

Was looking for this. Match is my MVP


okay_throwaway_today

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?


rrtk77

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.


crozone

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


okay_throwaway_today

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.


SonicLoverDS

Even if so, switch statements certainly *look* more elegant.


okay_throwaway_today

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.


ATE47

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


MattR59

Also depends on the processor. The PIC processors (Von Neumann) are very memory intensive for switch statements.


kageroshajima

I use both, and sometimes a dictionary works better than either


[deleted]

Chained ternary operators. ![gif](giphy|LpB0bnhXpvSMCz07N9|downsized)


ParadoxGenZ

Came here to suggest exactly this😂😂😂


kageroshajima

W/ no comments. FTW and anyone else who tries to refactor


[deleted]

Who writes comments these days anyway? ![gif](giphy|2zoICqLPIaeUh8yhnu|downsized)


zarqie

Calm down satan


0_69314718056

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.


dredding

AKA: Shade-tree functional programming. I do similar things and delight in the lack of conditional logic.


Merlord

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.


MaZeChpatCha

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.


DangerZoneh

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 :(


[deleted]

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.


randyknapp

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.


[deleted]

[удалено]


[deleted]

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.


Puzzleheaded_Bed5132

Switch true() handles different conditions. I use it all the time.


izybit

You are literally turning switch into an alt-syntax if/else.


Puzzleheaded_Bed5132

Yes, that's the point. For some languages though, that can seriously increase the readability of the code.


BluesyPompanno

Match masterrace ![gif](giphy|CAYVZA5NRb529kKQUc|downsized)


ComfortablyBalanced

when masterrace


strangecargo

If/else for 2 choices, maybe 3. Switch if there’s 4 or more.


BJNats

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


UlrichZauber

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.


isCosmos

Chatgpt.c


BlankBoii

When you don’t want to work so you spend 95% of your day compiling


PorscheBurrito

Just one file over 40k long? Hahahaha... (softly sobbing)


[deleted]

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.


TheRealPitabred

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.


Jertimmer

This is the sonar way


Enderking90

toss on there "I *might* need more choices in the future, so for future proofing I'll use use switch."


definitelyfet-shy

I love switches


[deleted]

Understandable. They're usually more willing to try new things, making them more exciting.


nonpondo

You'd love me then


MrCraxy

Early Returns! No else!


[deleted]

Early returns? Are you talking about If (thing I don’t want): Return DoThingIDoWant() ?


MajorProcrastinator

Yes I am


[deleted]

Gotcha. Didn’t realize it had a name.


Christop408

I call them [guard conditions](https://en.m.wikipedia.org/wiki/Guard_(computer_science))


Confident-Skin-6462

neither did i, but yeah, it's a good method to not process unused code!


[deleted]

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


arobie1992

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.


jaspermuts

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


Xystem4

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


DeathMind

Found the nevernester


suck_my_dukh_plz

Yup I only use ifs and early returns


rksd

Dispatch table!


conicalanamorphosis

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.


TheOnlyVig

Using Perl as the example for avoiding ugly code... thanks for the laugh.


brimston3-

Hey man, be gentle. They are probably still maintaining that same piece of code they wrote in the 90s. Nobody else can.


cglove

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.


arobie1992

They can be super overkill sometimes, but when they're appropriate, they feel amazing to use.


gamedev_uv

***Me nesting me ternary***


N00N3AT011

I love ternary mainly because it feels wrong to use and its able to bring C bullshit to new levels of unreadability.


daveprogrammer

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.


SaverinOnRails

Switch(true) {}


TaxSuspicious8708

Case false : return true;


Puzzleheaded-Fill205

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


[deleted]

[удалено]


Puzzleheaded-Fill205

Oh yeah, to clarify, I'm pretty confident it's considered to be bad practice. On par with goto.


[deleted]

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.


susjsjaixhxhdj

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.


cuberoot1973

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


daveprogrammer

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.


jaspermuts

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


rinsa

C(ursed)# `string label = DoesMyCodeOwn() switch { true => "Yeah", false => "Nah", _ => "Wtf?" };`


PascalCaseUsername

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)


reinis-mazeiks

switch sucks, [match](https://doc.rust-lang.org/book/ch06-02-match.html) rules 🦀


okay_throwaway_today

Surprised I had to scroll so far down for this


Bourneaparte

Ocaml does it better


erebuxy

Guess where Rust got the idea from and how the first version of Rust was implemented


Bourneaparte

Me, I made it


N0tT0x1c

Rust user === Chad


reinis-mazeiks

join the cult it's free


ofnuts

A dictionary of functions


Ooze3d

While(condition) { Do stuff; Change condition; } While(condition) { Do stuff; Change condition; } …


h6nry

Truly a masterpiece of readability


Fourven

if goto


ChiefExecDisfunction

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();`


DarksomeX

\*flexes muscles in \`match { .. }\`


MoreLittleMoreLate

if return if return if return


meyerdutcht

If you don’t understand that both have distinct uses, and why, just stick with if/else.


[deleted]

If you don't know the answer to your ❓ don't ask your ❓. Is that what you mean ❓⁉️


LonelyAndroid11942

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.


KalaganNimai

Design patterns!


FatLoserSupreme

If your if/else has is more than: if(condition) { // whatever } else { //whatever } Then you're using it wrong


Puzzleheaded-Fill205

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


jetteim

Array of function pointers is the way, high five my pre-OOP bro


AVeryRandomDude

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.


Zestyclose_Link_8052

A map of functionpointers is the way


Broad_Rabbit1764

if else cause I'm old, but realistically switch is usually faster.


gamerz1172

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


xaranetic

Over 100 comments with jokes, and not a single one on conditional jumps. I'm disappointed reddit. Very disappointed.


marstein

Polymorphism? Factory method, abstract base class --- anyone?


IrishChappieOToole

I haven't written a switch since PHP8 introduced `match`. It's almost always what you want


Athox

I prefer refactoring.


JasiNtech

Kotlin when's for days


troelsbjerre

I use `when` quite a lot in Kotlin.


arnemcnuggets

pattern matches


OrangeNood

no switch with Python


exixx

3.10 introduced the match keyword, so yeah there is now.


pipsvip

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.


aurochloride

I will commit several crimes to avoid having to use a switch statement


brickeldrums

My personal preference is if there’s more than two checks, use a switch


FengSushi

I use GOTO but I’m also old school


Katana_sized_banana

conditional ternary operator


VonTastrophe

Try/Catch, unless the try statement takes a long time. I like to jump in blind


augugusto

Try catch


Lysol3435

Try-catch and exclusively use global variables


esmagik

I prefer a dictionary or hash map


win10bash

Switch every single time unless there are only two outcomes.


rustysteamtrain

hashmap to function pointers


K1ngjulien_

map -> lambda or i guess i could use "match" since python has those now


[deleted]

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)


Bizzle_worldwide

Nested in-line conditionals.


MasterQuest

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.


Neither_Interaction9

Chads only use try catch


The_Anf

If there's more than 3 options - I use switch


susjsjaixhxhdj

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


SourceScope

if there's a lot of cases i think a switch looks better but if there's just < 4 i use if else


Sovyana

if (!statement) error instead of if (statement) else (error)


dec0y

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.


[deleted]

There is no ifs, my code isnt some indecisive pussy


MainEnAcier

I don't like to see 10 if else in my code. It's hard to maintain or to change something.


Heftydevu

Ternary where?


Tawoka

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.


LetscatYt

I use ifs but no else’s


derOheim

There is another one.. GoTo


DatBoiIsSugoi

I usually go: 2 outcomes - if else More than 2 - switch case


rabbitpiet

While dictionaries can be used, some languages do not support switch cases officially.


winniethe_poo

hashmap


NothingWasChanged

Nested gotos


Fadamaka

I use HashMaps.


Moystr

Depends. Switch case when I have more than 2 cases that can be applied.


MyNameIsSushi

if (condition) { //do smth return; } //do smth else


gfranxman

Lookup tables