Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
C0D4667776yWhat’s wrong with switch(true) ?
There’s times you just don’t want to write if/elseif all day long.
I almost used one yesterday, but managed to find a more common element to switch on and then add the hand full of extra conditionals into the default:; -
I don't understand how
switch(true){
}
is more readable than:
if(true){
}
if he was switch on variable, I'd understand it and agree is more readable, but I still go with an if/else tho -
@gintko @C0D4 @gitpush I may inform you all that it was a simple
if(aIsDefined) {
return ...;
} else if(bIsDefined) {
return ...;
}
return ...;
I'd go with @gintko & @C0D4 if it was written as
switch(true) {
case aIsDefined:
return;
case bIsDefined:
return;
default:
return;
}
(Even tho imho this is shitty, too. If-elseif-else is a fucken simple pattern)
But it being written as
switch(true) {
case aIsDefined:
return;
case bIsDefined:
return;
}
return;
..is utter bullshit to me. I'm not saying it's wrong, I'm saying I don't like it.
You learn if-else as first branching method and switch-case is introduced to keep states of a variable managed, not whole comparsions. In my eyes this isn't more readable, it's just a "look how fancy you have to read it twice to get it".
Nobody can tell me they look at switch(true) and say "yo of course, that's completely normal". You'd always stumble over it. -
I’ve used while(true) but never even seen a switch(true) or if(true). What the use case?
-
C0D4667776y@toriyuno
If you're like someone I use to know.
But you would just write a if/elseif block and work it out.
I think it's more because you can, not because you should.
For example*:
Function whatIsIt($variable){
switch(true){
case is_array($variable):
echo 'array';
break;
case is_numeric($variable):
echo "number";
break;
default:
echo 'no idea what you just sent me';
break;
}
}
* that's harder to write on a phone than it should be 😂 - I take no responsibility if that's not production ready code or doesn't work.
Related Rants
switch(true) god yes please
rant
wtf
ifelse
legacy
php
code
2014
nice