God that explanation is so overly complex. If-else is for conditional execution based on a boolean expression (expressions which evaluate to true/false). Switch is used for conditional execution based on a set of discrete values (usually primitives - enum, int, char, string...).
It's better to use switch when you need to conditionally execute something based on range of discrete values - e.g. evaluating a keypress:
switch(key) {
case Keys.Enter:
// Handle Enter keypress
case Keys.Escape:
// Handle ESC keypress
default:
// Don't care
}
We could have easily written this using an if... else if... else block but this switch statement is easier to read, modify and extend later if e.g. we want to handle more keypresses.
That's literally it.
The switch statements “selects the execution of the statement often according to a keyboard command”.
That's an example of a use-case but that's by no means the only use of switch lmao, what on earth is this article? Were they getting paid per word?
He explained why. Organization. It gets confusing when you have multiple statements in an If Else. Evaluating key presses can possibly use well over 15 keys. (video games control mapping for instance)
Switch Cases are well organised and don't appear convoluted. I recommend using If Else when there's only a handful of possibilities. If it's more than 3 then Switch Case is the preferable method.
First, see what /u/ObliviousGuy32 said - then let's take the example from earlier:
switch(key) {
case Keys.Enter:
// Handle Enter keypress
case Keys.Escape:
// Handle ESC keypress
default:
// Don't care
}
If I want to handle a new key press it's easy, I just need to write new cases:
case Keys.LeftArrow:
// Handle left arrow
case Keys.RightArrow:
// Handle right arrow
I can also fall-through case statements if I want multiple keys to perform the same action:
case Keys.UpArrow: // no break - falls through to next case
case Keys.LeftArrow:
// Perform "go to previous" action
break;
case Keys.DownArrow: // no break - falls through to next case
case Keys.RightArrow:
// Perform "go to next" action
break;
All together now, with the missing break statements so it's clear how the fall-through mechanism works:
switch(key) {
case Keys.Enter:
// Handle Enter keypress
break;
case Keys.Escape:
// Handle ESC keypress
break;
case Keys.UpArrow:
case Keys.LeftArrow:
// Perform "go to previous" action
break;
case Keys.DownArrow:
case Keys.RightArrow:
// Perform "go to next" action
break;
default:
// Don't care
break;
}
See how I added those lines without having to modify any of the other lines of code? It was super easy to just insert new case statements into the existing switch block. The cases I added are easy to read and understand.
Here's the original example with if... else if... else:
if (key == Key.Enter) {
// Handle Enter keypress
else if (key == Keys.Escape) {
// Handle ESC keypress
}
and with our new Up/Down/Left/Right key handlers:
if (key == Key.Enter) {
// Handle Enter keypress
} else if (key == Keys.Escape) {
// Handle ESC keypress
} else if (key == Keys.UpArrow || key == Keys.LeftArrow) {
// Perform "go to previous" action
} else if (key == Keys.DownArrow || key == Keys.RightArrow) {
// Perform "go to next" action
}
That's much less readable than the version using switch statements. The conditional statements are becoming more complex. I have to write a bunch of boilerplate key ==.
Both snippets of code do the same thing but good code does more than just work, it's also easy to read and understand.
Thank you, i have had it come up "why arent you using switch statements" for controller input with 4 buttons and couldnt think of a clear reason why i should since (i could be wrong here) if else handles priority and prevents multiple key press and will always stop at the top most level, multiple if will handle multiple input at the same time and that was all i needed
Maybe George Boole himself will resurrect and completely change boolean algebra. Quantum-boolean algebra where a boolean can also have a superposition. Neither true nor false. It's called "Maybe".
There's more than one way to branch on booleans! Lets not forget that Smalltalk would have you send the if message to a boolean with the two branches as arguments.
The first line is a simple boolean expression. checksleft is our integer, as initialized by our Checking class. It is sent the message <, and the argument 1. The current number bound to checksleft compares itself against 1, and returns a boolean object telling whether it is less than 1.
Now this boolean, which is either true or false, is sent the message ifTrue:, with an argument which is called a code block. A code block is an object, just like any other. But instead of holding a number, or a Set, it holds executable statements. So what does a boolean do with a code block which is an argument to a ifTrue: message? It depends on which boolean! If the object is the true object, it executes the code block it has been handed. If it is the false object, it returns without executing the code block.
So ultimately, the actual condition check is done using polymorphism!
75
u/[deleted] Sep 01 '21
This sub was all about the case statement a week ago. Now you're mad? Can't make anyone happy anymore.
/joke
23
u/pyker404 Sep 01 '21
Me looking the inner code looking for patterns: that's ok.
Me after realize the first comment: CONFUSED SILENT SCREAMING
19
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Sep 01 '21
Image Transcription: Screenshot
[In the screenshot, the IDE has underlined the final
break;, and the tooltip showing reads:]CS0162: Unreachable code detected
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
8
u/I_Am_Solar_Powered Sep 01 '21 edited Sep 01 '21
We use switch "when" statement with boolean in Kotlin and it is completely fine to do it.
Edit: fixed typo
6
u/Sevigor Sep 01 '21 edited Sep 01 '21
Lol. I mean maybe if
inFormationis nullable, but still not a great way to handle it.6
u/Mephob1c Sep 01 '21
I mean hey, future-proofing, it'll be easy to add new cases if/when bool is updated to have more possible values!
1
u/NekkoDroid Sep 01 '21
I don't even have so much of a problem with the switch, my problems are:
eventwith delegates3
u/Isvara Sep 01 '21
The real issue is that they're not matching on
file_not_found.2
u/Isvara Sep 01 '21
There's more than one way to branch on booleans! Lets not forget that Smalltalk would have you send the
ifmessage to a boolean with the two branches as arguments.2
u/FoxRaptix Sep 01 '21
I feel like a lot of this sub is just making fun of people that just started coding probably.
2
u/superslayer104 Sep 01 '21
Sassy comments are the best comments. You get to see the personality behind the programmer.
2
u/GLIBG10B 🐧 Gentoo salesman🐧 Sep 05 '21
Damn, the compiler detects that? I wonder if it would detect
case -2147483648throughcase 2147483647, followed by a default.3
u/pvic234 Sep 01 '21
Why not? I'm new.
2
u/karisigurd4444 Sep 01 '21
I like the casing on "inFormation".
1
u/Aperture_Executive2 Sep 02 '21
I smell unity.
1
u/[deleted] Sep 05 '21
ah yes,
-4
u/sixtyfifth_snow Sep 01 '21
Well, isn't it C#? I thought Visual Studio was not that stupid but now I think I was wrong.