• Quite (unregistered)

    Aha -- I've found TRWTF -- it's using this:

    updateObj.firstname = req.body.profile.firstname;

    ... instead of using something like:

    updateObj.setFirstname (req.body.profile.firstname);

    (takes a bow)

  • Paul M (unregistered)

    that's genius-level evilness

  • Long time lurker (unregistered)

    I must admit I can imagine some valid use cases for such a construct. Anyone else?

  • Spike (unregistered)

    I had a colleague who used this construct all the time for error checking. For this particular language, a switch statement was lowered to a series of if then else's anyway. It worked well enough and it's comprehensible.

    Throwing exceptions can be more concise if your language supports them.

  • Kabi (unregistered)

    I think I've seen something like this on stackoverflow vears ago... found it: http://stackoverflow.com/questions/14118996/is-switchtrue-valid-javascript

    So, seems to be common practice in Javascript and PHP. (Ladies and Gentleman, TRWTF)

  • Rouslan (unregistered)

    I would be far more concerned about the below line of code as it seems to imply that passwords are stored in cleartext on the server and are also sent in cleartext on the wire....

    case client.password != req.body.profile.password:

  • isthisunique (unregistered) in reply to Paul M

    There's a weird case in C somewhere where it makes a strange optimisation with a particular compiler and version I read ages ago.

    I think I've used something like this around two times in strange cases but double ironically because I needed readability and didn't care about performance.

    The problem is in this case, youtube, OOIOO, be sure to loop. Programming wisdom song playlist in youtube is essential.

  • Not Registered (unregistered) in reply to isthisunique

    You may be thinking of Duff's Device: https://en.wikipedia.org/wiki/Duff%27s_device

    I occasionally work on embedded systems with compilers that don't optimize this special case of writing to memory-mapped output registers properly (even though it is a common case) so Duff's device can cause real improvements in systems with even small read caches.

  • StephenCleary (unregistered) in reply to isthisunique

    Duff's Device, maybe? It's not particular to a compiler/version, but it has been known to cause insanity: https://en.wikipedia.org/wiki/Duff%27s_device

  • Mathijs (unregistered) in reply to Quite

    But getters and setters are not a good thing in JS

  • ummm... (unregistered)

    I have used this syntax couple of times, makes sense on some (rare) occasions.

  • (nodebb)

    Ah, the wonders of Javascript, that doesn't require case expressions to be compile-time constants...

  • SwiftAusterity (unregistered)

    Honestly this is used a LOT in vb.net code. It infuriates me and I refactor it every time I see it but I get to see it at least once every few weeks working on other people's vb apps.

  • Koen van Dratel (unregistered)

    It's all about constency... if 'update' doesn't mind that 'updateObj' may be undefined and If 'res' promises to send only the first 'send' and if the check for password equality is actually a check for password equivalency by means of magically overloading ':=' using instantaneous server interaction and if the inner switch is generalized into a loop iterating over the updatable properties and if the user appreciates a successful update message after updating to exactly the current values and if 'exec' can't be upgraded to selectively yield 'done' or 'fail' ..then the only WTF is using '? : ' instead of a switch.

  • Stefan (unregistered)

    Fun fact: In Golang, you can omit the expression after the select, and it will imply true. Such a switch is idiomatic in Go.

    Although it should be noted that Go switches do not fall through.

  • Carl Witthoft (google)

    Wait... someone would prefer if -then -else if -then- else if-then .... ????

    Case lists are much easier to read,not to mention easier to add or remove one case. Try pulling one "case" out of the middle of heavily nested if-else constructions.

    My complaint is that either setup will only correct one item each time thru -- why not set it up so all conditions are tested regardless of the outcome of th previous test?

  • Alsot (unregistered) in reply to Carl Witthoft

    The inner switch statement lacks breaks so it'll keep falling through and set all of the items on the first go.

  • jgh (unregistered)

    I thought people had known about this for yonks. I first came across it in about 1988.

  • Carl Witthoft (google) in reply to Alsot

    Ok, understood. That's not how R and Matlab handle "switch" so I forgot what c-ish langs do

  • Pudge601 (unregistered)

    This code does have a lot of WTF, but am I the only person who is somewhat disgusted at the crossbred abomination between a promise and a NodeJS style callback at the end:

    .exec()
    .then(function(data,err){
    

    If exec is returning a Promises/A+ (https://promisesaplus.com/) 'thenable' object, then I'd expect 'then' to be a function taking 2 callbacks as arguments - one for the success case and one for the failure case. This is like someone tried and failed to promisify a NodeJS function.

  • onitake (unregistered)

    I actually encountered a case where the compiler would produce superior machine code from an if .. else if .. else construct than a switch statement. This was avr-gcc, and the target MCU had only 128 bytes of RAM, however. I tried to massage some sanity into the output, but ended up with a chain of ifs. For some reason, avr-gcc insisted on occupying RAM with a lookup table and wasting additional code space with a generated flash-to-RAM copy routine. Awkward.

  • davej (unregistered)

    The standard situation where the code wasn't tested and doesn't really do what it was supposed to do. Plain old if's would be more compact than the switch and would actually work!

  • obviouslyfake (unregistered)

    I remember doing that in BBC BASIC V. Surprisingly useful (and clear), even without fall-through.

  • Fundamental (unregistered) in reply to SwiftAusterity

    ... In VB.Net, perhaps it's because people copy the idiom from another language. With some excuse, since "VB.net" is the language that pretends to reproduce the idiom of another language.

    In line-oriented languages, there is no requirement or expectation that case labels only work with "computed goto" statements.

  • (nodebb)

    I don't think the outer switch(true) is particularly a problem. In some cases this sort of idiom can be clearer than a set of nested ifs. I've used it both in SQL (though now I'd usually just use a case statement) and in Informatica, using the syntax DECODE(true, ...). In Informatica in particular this can be very useful if you need to evaluate several different conditions along the way to getting a result, and far clearer than a long nested if chain.

    The inner switch(true) in this case is just silly though. That should definitely have been written as a series of ifs.

  • Homerun (unregistered)

    This is more readable than a lot of nested if-then-elseif nonsense that I've encountered. The condition is close to the executing code and can be readily seen, and indentation separates all the cases nicely. It's not "idiomatic", but so what? Maybe the idiom needs to change. The current idiom of if-then-elseif is broken as fsck, as you would know if you've ever had to wander the maze of insanity that some people seem to enjoy putting other programmers thtrough.

    Is there some non-syntactic reason why this code isn't good?

  • Bert (unregistered)

    Just a shame Javascript doesn't have goto.

  • Darth Killer (unregistered)

    That one is actually a years old practice that keeps poping up here and there, but in no way is it an advisable practice, despite being interesting-looking.

    First problem is performance. Switch is not meant to have to evaluate an expression in the "case" statement, even if it can, and as a result will not be as good in this form as its classic if-elseif-else counterpart.

    Second problem is about conditions combined with OR in if-elseif-else. When translating that to this switch statement tactic, you can use one case with the same combined conditions, or you an divide the conditions and give them separate cases without breaks, like so (PHP) :

    switch(true) { case $condition1: case $condition2: // stuff break; default: // stuff }

    Only problem, because there's no explicit OR operator in this case, if $condition1 matches, you'll evaluate $condition2 regardless, while you would not have if there were an OR operator. This will lead to unexpected behaviour in some cases, like when you were counting on that OR to prevent evaluation second condition if first one passes. Like this one :

    switch(true) { case !isset($_POST['var']): case $_POST['var'] == '': // Error : unknown index // stuff break; default: //stuff }

    Bottom line : while this use of the switch may look interesting and is nothing new, don't use it. :P

  • Darth Killer (unregistered) in reply to Darth Killer

    Sorry about failing to indent my PHP code, looks like i'll have to check the manual about how to do it here... :-° It was indented properly before i submited...

  • Meh (unregistered) in reply to Long time lurker

    Not me. There's better ways to compare 2 objects with matching property names, and populating a 3rd changes object with differing fields. A series of ifs without elses would be one.

    Same holds true for breaking out of a routine if certain conditions are not met during input validation

  • dudeNumber4 (unregistered)

    Seems to me, apart from performance considerations in some circumstances (certainly not here), this is perfectly fine. Like someone else mentioned (they hated it, I liked it), in VB "select case true" was a great construct.

  • Fabio Milheiro (unregistered)

    I don't think that is much different from if statements.

    I can read it but not that readable. If that was the goal, I think it failed.

  • Oh please (unregistered) in reply to Not Registered

    "I occasionally work on embedded systems..."

    Just because your shitty PHP app is running on a server in a datacenter does not make it "embedded."

  • Joseph Osako (google)

    What, no one mentioned the '(cond)' form in lisps? For Shame.

    What's that you say? Only freaks like me use Lisp? Damn, I forgot again....

Leave a comment on “Now There's a Switch…”

Log In or post as a guest

Replying to comment #:

« Return to Article