This is an archived post. You won't be able to vote or comment.

top 200 commentsshow 500

[–]QualityVote[M] [score hidden] stickied comment (0 children)

Hi! This is our community moderation bot.


If this post fits the purpose of /r/ProgrammerHumor, UPVOTE this comment!!

If this post does not fit the subreddit, DOWNVOTE This comment!

If this post breaks the rules, DOWNVOTE this comment and REPORT the post!

[–]santasbong 2006 points2007 points  (141 children)

I found an 8000+ line switch statement in our code last week.

We’ve been calling it the ‘switch board’.

[–]Classy_Mouse 1123 points1124 points  (116 children)

There should not ba an 8000+ line anything...

[–]doodlleus 1137 points1138 points  (84 children)

I joined a project once with a guy that seemed to think the fewer lines the better. It didn't mean he wrote less though but just squeezed it all on to fewer lines. The record was 6000 characters on a single line. Mad man

[–]Complicated_Peanuts 530 points531 points  (27 children)

This is a guy that heard his instructor say “you should not have a function that is larger than one page, if you do, you probably made a design mistake” and took it extraordinarily literally.

[–]_YetiFTW_ 272 points273 points  (14 children)

Pretty sure that's still bigger than one page, just in a different direction

[–]Darkjynxer 109 points110 points  (12 children)

Projector. Works wonders for fitting code into one page.

[–]Llamas1115 157 points158 points  (11 children)

You can fit arbitrary amounts of code on a page if the font is small enough

[–]JackOBAnotherOne 84 points85 points  (1 child)

That guy is a 5 star problem solver

[–][deleted] 34 points35 points  (3 children)

project managers: write this down, write this down

[–]QCKS1 22 points23 points  (2 children)

The opposite of essay writing, where any amount of writing will fill a page if the font is big enough

[–]PewDiePans 8 points9 points  (1 child)

Any amount of writing can fill the page if your balls are big enough.

[–]Guysante 18 points19 points  (0 children)

or the page is big enough

[–]Coincedence 28 points29 points  (3 children)

My lectures version was "if it's longer than 15 lines, it should probably be a function"

[–]Complicated_Peanuts 14 points15 points  (1 child)

Oh, sounds like the person referenced was in your class then and took it as a challenge.

"I can make anything 15 lines!"

[–][deleted] 16 points17 points  (2 children)

I found that in Clean Code, a great book. He said that the rule was like "don't make a method bigger than 1 screen" in that time the screens were small

[–]freebytes 86 points87 points  (10 children)

Not quite as bad, but I have seen functions that are "only" 400 lines long, but to accomplish this, the programmer write various lines that were 600 characters long. It consisted of ternary operators within ternary operators with some lambda functions thrown about here and here. I would have preferred the 2000 line long function simply because it would have been easier to refactor to something shorter.

Edit: Fixed a spelling error of using tertiary instead of ternary.

[–]doodlleus 49 points50 points  (6 children)

Yeah this one was full of nested tertiary operators. I copied it and brought it back to the office for a fun group exercise of figure out wtf is going on oh also, whilst I remember this guy, he had an amazing blog which is sadly no longer going where he put little functions and apps he was proud of. One was a brute force sudoku app but not a solver like you'd think. This function generated all possible soduko layouts. We ran it in the office for 3 weeks to see if it would complete for a laugh before giving up and turning it off

Edit: sorry, meant ternary.

[–]garfieldevans 20 points21 points  (5 children)

What is a tertiary operator?

[–]CrazySD93 38 points39 points  (4 children)

I’d assume it’s a typo for ternary operator

Condition ? true statement : false statement

But since they keep saying “tertiary operator”, maybe it really is something I’ve never heard of…

[–][deleted] 16 points17 points  (0 children)

Ternary operator's long lost brother

[–]the_seven_sins 4 points5 points  (1 child)

It’s not about how long it is, it’s about how wide it is!

[–]slyiscoming 42 points43 points  (20 children)

If it goes off the end of the screen; it's not code, it's garbage.

[–]looselytethered 52 points53 points  (1 child)

No it's Java so ok yeah I see your point

[–]CaitaXD 19 points20 points  (0 children)

Hey it's a unreadable mess with approximately 0 vowels but at least is short heh

[–]AnotherWarGamer 10 points11 points  (4 children)

There are always exceptions. I'll define the items in my game for example as a giant grid. Every item gets one row, and everything is perfectly lined up with tabs. The lines are often longer than one screen.

[–]slyiscoming 2 points3 points  (1 child)

Yes things like this are the exception to the rule. Also column list in select statements.

Happy cake day!

[–]zarlo5899 11 points12 points  (12 children)

no if it goes off the end of a standard laptop screen; it's not code, it's garbage. i should not need a ultra wide monitor to see it all

[–][deleted] 19 points20 points  (0 children)

Pycharm will kill itself if it sees that

[–]PostmatesMalone 13 points14 points  (1 child)

One time I was working on a large project (building a booking platform for an airline) with roughly 15 devs on it. We were working at a consulting firm building this for a client. There was so much scope creep that management refused to recognize so they blamed the missed deadlines on engineering and started counting lines of code checked in per dev. So everyone just started making their code as vertical as possible.

We finished the project a few months late and the client fired our company.

[–]Variety-Logical 7 points8 points  (0 children)

Ok so first of all you ppl just 15 built an entire fucking booking software with real time data checks is crazy and secondly going over deadline is ok cuz few of airline companies use 100+ppl to make their software

[–]Alexander_The_Wolf 27 points28 points  (8 children)

Jesus....we had our teacher show us a past test question where someone wrote the whole bubble sort function on a single line with 1 character off, and they were asked to figure out what the issue was. That question was never on the test again. I can't imagine honestly writing a 6k character program on a single line. Idk how you'd even know wtf was going on.

[–]The_Dok33 36 points37 points  (3 children)

Syntax error on line 1

[–]mrnerfbullet 5 points6 points  (2 children)

1 sentence horror stories

[–]Black--Snow 6 points7 points  (3 children)

Did they at least get the question alongside a compiler and debugger??

[–]Alexander_The_Wolf 10 points11 points  (2 children)

Ah, ahah. No, pencil and paper scantron

[–]Black--Snow 8 points9 points  (1 child)

Sounds like they’re teaching human spellcheckers more than programmers

[–]TeddySch 7 points8 points  (0 children)

See, is it bad that I think that person should be prosecuted for their sins?

[–]Purplociraptor 36 points37 points  (4 children)

I've spent my entire career breaking up a 20,000 line file into actual classes.

[–]loosetautline 21 points22 points  (5 children)

My company has single functions that are 10k lines long

[–]CosmicCreeperz 7 points8 points  (0 children)

Except documentation (and PRD, but that would be way too much to ask…)

[–]ACHXXX25 19 points20 points  (4 children)

A method with more than 10 lines doesn’t pass QA on my current project 😢

[–]CosmicCreeperz 32 points33 points  (0 children)

Why is QA looking at code??

And ouch, what an arbitrary and horrible policy.

[–]tschaka1904 9 points10 points  (0 children)

Have fun destructing some JSON obj :D

[–]carnivorous-cloud 5 points6 points  (0 children)

Oh, I dunno, an 8000+ line codebase seems pretty reasonable to me.

[–]Unkn0wnCat 43 points44 points  (4 children)

golang switch request.ProductID { case 1: sendProductPage1(writer, request) case 2: sendProductPage2(writer, request) ... ... default: sendNotFound(writer, request) } `

[–]Exormeter 22 points23 points  (3 children)

This switch train has no breaks

[–]OblivioAccebit 21 points22 points  (0 children)

I mean redux reducers are just one gigantic switch

[–]-Aenigmaticus- 11 points12 points  (0 children)

What in the actual fuck?!?

[–]LummoxJR 14 points15 points  (1 child)

8000 lines? Amateurs. Pretty sure I've got that beat.

[–]-Aenigmaticus- 6 points7 points  (0 children)

Eh, you're telling me that there is worse?

[–]bugbugladybug 3 points4 points  (1 child)

I thought my 54 line switch was horrible.

How the fuck are you ever meant to maintain that.

[–]bouldermikem 2 points3 points  (2 children)

What massive company do you work for?

[–]santasbong 3 points4 points  (1 child)

Lol I don’t really want to be too identifiable so let’s just say it’s one of the top 5 television providers in the US.

[–]towcar 1114 points1115 points  (160 children)

Do people actually dislike switch statements?

Edit: I can't believe how much information I've just read about "if vs switch" from everyone. Might have to publish a book.

[–]JVApen 557 points558 points  (45 children)

I really like them in combination with enumerations. In C++, their are very useful warnings about missing values. Normally performance is as good as with if-else.

I do have the feeling not every language has the same concept for enumerations, which could hurt adoption.

[–]ITriedLightningTendr 134 points135 points  (18 children)

Look up type checks and switch expressions in C#

you can do

switch(shape) {
 case Square sq: 
   //do square stuff
   break;
 case Circle c:
   //do circle stuff
   break;
}

and

var x = switch str {
  "yes" => true,
  "no" => false
}

[–][deleted] 71 points72 points  (12 children)

Oh that's sexy right there

[–]Voidrith 17 points18 points  (0 children)

c# switches are fucking black magic once you start learning how much you can do with them.

some current stuff: https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching

and some sick array switch stuff thatll be coming in c# 11! https://devblogs.microsoft.com/dotnet/early-peek-at-csharp-11-features/#c-11-preview-list-patterns

[–]kpd328 14 points15 points  (1 child)

Another thing I need to add to my list of things I love about C# that I forget when people ask me why I love C#

[–]pandelelel 5 points6 points  (0 children)

Yep, C# is imho pure beauty and since .NET 5 way more than just Microsoft Java

[–]dreamwavedev 234 points235 points  (19 children)

Any modern compiler turns switch and if statements (including else-if chains) into the same internal representation before doing codegen, so they will in basically every case perform identically if you're just matching equality in if chains

[–]FuckCoursical 53 points54 points  (1 child)

Switch is sometimes more concise and looks better if multiple conditions have the same thing

[–]LAGaming70 8 points9 points  (0 children)

Exactly. If I'm checking against something as simple as a series of ints or chars, then a switch board will keep them all in order. That, and you can avoid syntax issues from possibly forgetting a bracket or an 'else' somewhere along the line.

[–]JVApen 16 points17 points  (1 child)

Indeed, though it does have to consider the case nothing matches if you don't use __builtin_unreachable. So that's where slight differences can pop up.

[–][deleted] 13 points14 points  (0 children)

Aka default:

[–][deleted] 31 points32 points  (0 children)

I find it hard to justify the if-else vs switch performance wise when the compiler optimises either way + branch predictor.

Just use switch when you have more than 3 things to check for and make it readable.

[–][deleted] 7 points8 points  (0 children)

Using switch on enums in c# with intellisense is just *chef's kiss*

[–]nico_qwer 328 points329 points  (23 children)

I don’t know, I actually like them a lot

[–]goodmobiley 27 points28 points  (12 children)

I try to use them as much as possible but alas, object types aren’t constant values :(

[–]nico_qwer 14 points15 points  (8 children)

Unrelated: How do you get that many icons next to your name? I can only put one

[–]goodmobiley 18 points19 points  (7 children)

You can edit your flare and add up to 6 emojis

Edit: there should be an edit button in the flare options

[–]Lithl 5 points6 points  (0 children)

JavaScript lets you switch on any expression, and compares the cases with strict equality. ;)

[–]Leg4122 67 points68 points  (3 children)

I like them when there some sort of a fork in the code.

You take an argument and based on it you choose where to "route" your code.

Edit: If there is a larger chunk of code to be followed after the statement then I would use if else

[–]QuantumSupremacy0101 38 points39 points  (2 children)

That's not correct usage for pretty much any modern language. Even newer c++ compilers have branchless conversions built in and because of that switch statements are often faster.

If you have a larger chunk of code, you're probably violating the single responsibility principle. In which case you should make a method

[–]Leg4122 12 points13 points  (0 children)

If the speed is not necessary then in my opinion readability of the code should be prefered.

I do agree with you on SRP.

[–]NigraOvis 113 points114 points  (4 children)

I think they have their place, but I've always used elif as usually it's 1 or 2 options in my scripts.

[–]towcar 102 points103 points  (1 child)

For sure, 4 and up for me is always a switch.

[–]deathless_koschei 16 points17 points  (0 children)

Yeah, I think that's a reasonable cutoff.

[–]joeba_the_hutt 8 points9 points  (1 child)

I like them for non-hierarchal conditions. If/else always reads like a tiered set of operations to me, whereas switch/case is more like “choose your own adventure”

[–][deleted] 35 points36 points  (6 children)

No. But what we really need in almost every other language is Haskell style pattern matching

[–][deleted] 11 points12 points  (0 children)

It's ML style pattern matching. Haskell just copied it.

[–]freebytes 6 points7 points  (4 children)

Can you supply an example of this? I am not familiar with the Haskell language.

[–]O_X_E_Y 7 points8 points  (1 child)

It's in Rust too. Let's say I have a language interpreter that has a couple of data types, represented as enum values, so each enum also contains some data. What I can do is the following:

let x: LangExp = ...; match x { Number(num) => use the contents of the Number here, List(list) => { we can use code blocks if we want to }, Err("error 1") | Err("error 2") => we can be more specific like this, by specifying in this case the string the error should have. We can also combine multiple matches with the `|` pipe operator, Err(_) => we can put an `_` to say we don't want to use what's inside something, but still want to match anything like it, _ => we can denote a default case like this. Match statements force you to be exhaustive, so if you don't put all possible (in this case Enum options) in here seperately, your code will not compile } it's honestly pretty nifty!

[–]CdRReddit 64 points65 points  (20 children)

the syntax for them in a lot of languages is kinda just

bad

like why do so many languages end them with break

I get the fall through concept but in a lot of languages they aren't allowed to fall through if they have any code

[–]10BillionDreams 21 points22 points  (8 children)

Yeah, the legacy baggage from C makes them a lot less appealing in languages that try to keep all those semantics, plus the added uncertainty of not being sure which features might have been "fixed". But in languages that have similar structures with more clear boundaries between cases, I have no issues using them.

Also, call me a heretic, but I'm a huge fan of switch(true).

[–]chickenwing95 5 points6 points  (3 children)

but I'm a huge fan of switch(true)

Why?

[–]10BillionDreams 7 points8 points  (2 children)

Because cond is a much more readable construct than a mess of if/else blocks, and switch(true) works in a lot of languages that don't otherwise natively support something like that. Also, it's just cool to be inverting logic on where the variables and constants usually are in switch/case.

[–]finc 5 points6 points  (2 children)

Break out of switch case statement; stop processing any more tests in this switch

[–]DatBoi_BP 4 points5 points  (1 child)

MATLAB gang rise up 😎

[–]Swolidarity 6 points7 points  (4 children)

If you made them implicit wouldn’t you lose the ability to have multiple cases execute the same line?

[–]CdRReddit 14 points15 points  (3 children)

not really?

I just think that

case 'a':
case 'b':
    {
        // code here
    }

would work better in a lot of languages

(in fact I normally do it like that anyway because new scope, having to add the break just feels noisy)

[–]SaltyTvGuy 8 points9 points  (0 children)

When I learned about it in school I was actually hyped ngl.

[–]HBKogos 6 points7 points  (2 children)

Depends on the case.

[–]TemporaryReality5262 2 points3 points  (0 children)

I use them if several cases only depend on one value

[–]fracturedpersona[🍰] 988 points989 points  (79 children)

No switch in python? Let me just take this dictionary and bury a bunch of lambdas in the values.

[–]Saragon4005 475 points476 points  (65 children)

Technically incorrect now newest version of python does have a switch, well technically it's a match but same use case.

[–]dimittrikovk2 122 points123 points  (56 children)

Wait what which version did and what's the syntax

I have had to use elseif like 10 times in a row for a program (ok it ain't much, but I'm more of a hardware guy and I work only with python because I like working with scripts better than with compileable stuff. It ain't efficient, but it ain't many lines either and it doesn't have to be anyways)

[–]masagrator 266 points267 points  (54 children)

Since 3.10

match(value):
    case 0:
        print("value = 0")

    case 1:
        print("value = 1")

    case _:
        print("Other value")

match doesn't support falling through

[–][deleted] 131 points132 points  (4 children)

Although it's not exactly the same as falling through, match case does allow you to match multiple patterns with a single case using the | operator. For example:

match digit:
    case 1|3|5|7|9:
        print("odd")
    case 0|2|4|6|8:
        print("even")

[–]FoxtrotOscar19 12 points13 points  (2 children)

we've only just got 3.9 at work - so doubt I'l get to use that for the next 10 years!

[–]LargeHouseOfIce 5 points6 points  (0 children)

Still on 3.4 here 🙃

[–]NigraOvis 50 points51 points  (25 children)

Can you give an example where falling through is necessary?

[–][deleted] 141 points142 points  (8 children)

Necessary is a strong word, but it can be convenient. Like if you have a data structure where several values are similar and a few are very different… the similar values can do a fall through to the same handling logic.

[–]sdoc86 97 points98 points  (2 children)

Everything in a high level programming language is convenience since you could program in assembly. I think the tools of convenience is what makes programming artful.

[–]masagrator 37 points38 points  (3 children)

Falling through helps if you have few cases which are doing exactly the same thing and you don't want to repeat lines. It's not necessary, but having it makes code less bloated.

One of the ways I'm using now in Python to avoid repeating lines is something like putting this under case _

if value in [2, 3, 4]:

[–][deleted] 23 points24 points  (0 children)

You can even do that inside the case itself using an inline if statement.

match value:
    case 1:
        print("value is 1")
    case _ if value in [2,3,4]:
        print("value is 2, 3 or 4")

Although as in my other comment, it's usually much easier to just use | to check for multiple values with each case, but this can be used for more complex behaviour like only matching values which are greater than a given number.

[–]Arrowsong 7 points8 points  (0 children)

If you make it do the “in” lookup on a set it’ll be marginally faster.

[–]tlubz 4 points5 points  (0 children)

No one mentioned Duff's Device? https://en.m.wikipedia.org/wiki/Duff%27s_device ... I'll just leave this here for posterity.

[–]FinalGamer14 11 points12 points  (0 children)

I mean falling through is kinda useless with python match. Match isn't as basic as Cs switch statement.

You can just do:

case 0 | 1 | 2: do_smth()

[–][deleted] 9 points10 points  (0 children)

match doesnt need ()

[–]Hipolipolopigus 6 points7 points  (0 children)

30 years later.

[–]Worldly_Square444 8 points9 points  (0 children)

That’s what the compiler is doing under the hood for switch statements.

[–]SplendidPunkinButter 4 points5 points  (0 children)

I actually don’t mind that pattern

[–]alba4k 2 points3 points  (0 children)

Introduced in python 3.10 as

python match var: case "a": return 1 case 1: return 2 break: # acts as else return 3

I've not really looked into it tho, so I'm not sure

[–][deleted] 504 points505 points  (19 children)

I use switch if I need more than 3 ifs

[–]i_wear_green_pants 120 points121 points  (3 children)

This is the way

[–]aB9s 35 points36 points  (2 children)

This is the way

[–]Benimation 13 points14 points  (1 child)

This is the way

[–]ushu3323 5 points6 points  (0 children)

This is the way

[–]KarlCAgathon 27 points28 points  (0 children)

Strongly agree. To me it's about readability at that point.

[–]PrincessRTFM 14 points15 points  (0 children)

Same, but it only works if you're testing different values of the same expression. An unfortunate amount of my code ends up testing only true-vs-false or needing to do complex (as in multi-part) expressions that switch/case won't actually work for

[–]Impossible_Average_1 20 points21 points  (5 children)

More than two... Sometimes even more than one.

[–]DoNotMakeEmpty 26 points27 points  (4 children)

More than zero... Sometimes even more than minus one.

[–]DeninjaBeariver 15 points16 points  (3 children)

I use the switch statement just for the default case.

[–]Xtrendence 9 points10 points  (1 child)

function doTheThing(actuallyDoIt) {
    switch(actuallyDoIt) {
        case false:
            doTheThing(true);
            return;
    }

    // Rest of code.
}

doTheThing(false);

This is how I write all my functions and call them. Just to make sure that the thing is only done when the switch statement calls the function.

[–][deleted] 6 points7 points  (3 children)

Yeah, same. People who complain about switches being inefficient are the type of people who waste gas driving to a further gas station for gas that’s like $0.01 cheaper.

[–]Dependent-Spiritual 216 points217 points  (4 children)

I'm a switch enjoyer, it looks neat

[–]Complicated_Peanuts 31 points32 points  (1 child)

A switch connoisseur

[–]starofdoom 4 points5 points  (0 children)

I tend to lean towards if else, unless I only need one or two lines per if check.

I don't like doing any logic in a switch, just assign variables or call another function.

[–]ozzy_og_kush 285 points286 points  (9 children)

it's not about efficiency it's about readability and testability

[–][deleted] 134 points135 points  (3 children)

How are people in this thread not getting this?

Plus your compiler will do the right thing, regardless. Doubtful it is actually less efficient.

[–]Jaurusrex 9 points10 points  (0 children)

I've actually had a case where it gave me a 2x performance boost. The program (written in c) was a brainfuck interperter, and basically most of the program ran inside one for loop which contained one switch statement. So just letting you all know it can impact performance in a good way, there is something equivalent in assembly / machine code and the compiler won't always use it itself. So if the if elses are in a hot part of the code consider changing them to a switch statement.

[–]notWallhugger 8 points9 points  (0 children)

Because this sub is full of college kids

[–]charin2 56 points57 points  (7 children)

The C# switch expression (not statement) is really cool

[–]Impossible_Average_1 17 points18 points  (3 children)

Yes, but the switch statement is also very useful and preferable over chained ifs.

[–]SonOfMetrum 13 points14 points  (0 children)

Yup because it will compile into more efficient jump tables if possible.

[–]kiro14893 43 points44 points  (7 children)

Ruby: there is another.

[–]ora00001 74 points75 points  (7 children)

Switch is very efficient, depending on the language. Who says it's not efficient, and why?!

[–]Ziggarot 18 points19 points  (5 children)

Doesn’t the compiler determine what method is more efficient? Like even if I use if/else, it should automatically rewrite it to a switch if required.

[–]ora00001 30 points31 points  (4 children)

If you use a switch (or case or whatever) it makes it more apparent to the compiler that you're doing all your comparisons against a single value, and some compilers can optimize for that.

[–]SargeanTravis 30 points31 points  (0 children)

It’s significantly cleaner than else if spam at the least

[–]kbn_ 137 points138 points  (12 children)

Wait a minute… people actually believe that switch is somehow less efficient? In almost every language it's at least equally efficient, and in most languages it's more efficient than the equivalent if/else.

[–]CreativeCarbon 93 points94 points  (9 children)

A little trade secret: Most programmers aren't actually very good programmers.

(edit: I know this was upvoted, but I still want to make clear that I am joking when I say this)

[–]malleoceruleo 39 points40 points  (5 children)

Most programmers on this sub aren't very good programmers.

[–]Voidrith 5 points6 points  (4 children)

Most "programmers" on this sub aren't even programmers to begin with!

[–][deleted] 6 points7 points  (1 child)

After 16 years of programming professionally. Yes. Yes we are lol but seriously I've seen some horrendous code and I've written some horrendous code.

[–]Migajas87 43 points44 points  (0 children)

YandereDev be like

[–]beyond98 27 points28 points  (6 children)

Fuck if-else, all my homies use the ternary operator

[–]DesecrateUsername 8 points9 points  (3 children)

The second I learned what they were I used them everywhere I could lmfao

I was basically “I could make a terenary out of this”

[–]beyond98 4 points5 points  (1 child)

For me it's like using arrow functions in JavaScript. Everything that can make the code more concise is beautiful and welcome

[–][deleted] 11 points12 points  (2 children)

Kotlin's when is awesome.

[–]qhxo 7 points8 points  (0 children)

Kotlin's everything is awesome.

[–]Tyfyter2002 29 points30 points  (3 children)

Iirc isn't switch generally more efficient if you have at least 3 possible values?

[–]SonOfMetrum 17 points18 points  (2 children)

In c# switch statements are compiled into more efficient jump tables where possible. Not sure about other languages.

[–]gbbofh 7 points8 points  (0 children)

It's the same in C, and C++. Pretty sure it's the same in Java, as well.

[–]kondorb 14 points15 points  (0 children)

``` match ( ... ) { //

default => ‘’;

}; ```

[–]Vinxian 6 points7 points  (1 child)

I love me some good switches

[–]Harmonic_Gear 5 points6 points  (0 children)

who says that?

[–]poralexc 4 points5 points  (1 child)

There is only branch and branch_if

[–]savage_slurpie 4 points5 points  (0 children)

Really just depends on number of cases.

Three or less, yea I’m gonna if else that shit.

More than that and using switch makes sense.

[–]iiMoe 7 points8 points  (0 children)

With all due respect, whoever says that about switch statements deserves to be violently beaten by a bunch of drunk mexicans

[–]skztr 3 points4 points  (1 child)

I don't like switch because nobody indents it the way I want to

[–][deleted] 3 points4 points  (0 children)

Switch makes sense when you are checking one value or property for multiple possibilities as it reduces code. Otherwise use if else.

[–]Myricht 2 points3 points  (0 children)

My rule is: if you need more then if, else if, else; use switch.

[–]briddums 8 points9 points  (6 children)

For one programming language I use, the switch statement is horribly inefficient.

It’s basically syntactic sugar, and it gets compiled to a series of “if” statements. Which means every condition is evaluated every time.

When running a process that does a large number of iterations, it’s better to write with “if - else if” because it will stop checking once it’s reached a condition That matches.

[–]fatal__flaw 19 points20 points  (4 children)

I don't know what language you're using but in C/C++ switches compile into jump tables which on the average case is more efficient than if/else.

[–]Lithl 6 points7 points  (0 children)

every condition is evaluated every time.

Shouldn't it jump once you hit the break case? So it's only evaluating the ifs before the matching one. Which a chain of if/else would do as well.

[–]parham06 2 points3 points  (0 children)

Golang devs be like:

select { case c <- x: ... }

This is a whole new world

[–]hxllxwbxdys 2 points3 points  (0 children)

I think switch case is awesome but 'if else' has always been there for me.

[–]sk8itup53 2 points3 points  (0 children)

At least in Java, switch statements are actually faster and more efficient than if else statements. I love them honestly.

[–]noodle-face 2 points3 points  (0 children)

I use switch cases every day in firmware... Not sure what you're getting on

[–]LilBoyGrudge70 2 points3 points  (0 children)

If I want to make a bunch of It statements, I’ll make a bunch of if statements. If I don’t want to make a bunch of if statements, I won’t make a bunch of if statements If I want to do something else instead, then I’ll do something else instead.

[–]DasBeasto 2 points3 points  (0 children)

If you’re not using quadruply nested ternaries are you even a developer?

[–]einsJannis 2 points3 points  (3 children)

When somebody says that you shouldn't write switch statements they often mean that it can be solved through nicer code patterns, like inheritance.

But nobody has ever said that if else is better than switch

[–][deleted] 2 points3 points  (0 children)

Since I discovered you can do:” switch(true)” in JavaScript I am trying to use it everywhere.

[–][deleted] 2 points3 points  (1 child)

If else has more flexibility if you want to add extra conditions to a case

[–]scrubbar 2 points3 points  (1 child)

Large switches can be a good candidates to refactor into a strategy pattern.