Comments on: How to avoid switch-case syndrome https://j11y.io/javascript/how-to-avoid-switch-case-syndrome/ Sun, 22 Mar 2015 15:39:22 +0000 hourly 1 https://wordpress.org/?v=5.0.13 By: Floby https://j11y.io/javascript/how-to-avoid-switch-case-syndrome/#comment-1082 Sun, 09 Aug 2009 22:21:09 +0000 https://j11y.io/?p=989#comment-1082 @kzz : You’ll need to change this code, indeed. It simply doesn’t work, the value between the ‘case’ and the ‘:’ must be a constant value which is then compared (==) with the subject of the switch statement (switch(subject)). You may want to use a “else-if” structure.

if(i < 0) {
  //something
}
else if(i == 0) {
  //something else
}
else {  //use as default
  window.dump('i is strictly superior to 0, since i = ' + i);
}

I often use this in the same conditions as a switch but when I know that the first conditions are more likely to happen.

]]>
By: Martin Kirk https://j11y.io/javascript/how-to-avoid-switch-case-syndrome/#comment-1081 Mon, 27 Jul 2009 09:40:40 +0000 https://j11y.io/?p=989#comment-1081 … and because the lookup is used 2 times to find the element in the object.

]]>
By: Martin Kirk https://j11y.io/javascript/how-to-avoid-switch-case-syndrome/#comment-1080 Mon, 27 Jul 2009 09:35:25 +0000 https://j11y.io/?p=989#comment-1080 excuse me, but this MacGyver hack’on’crack code isn’t very good…

there is very good reasons when to use switch-case:
– when performance is an issue
– when each token i distinct (or nearly)
– when the context matters
– when other people read your code (as stated by Antonio)

i’ve used switch-case when formulating my code-parser in this way (which is the fastest and best way to do so)

var tokens = [
	'distinct1','distinct2','distinct3',
	'mixed1','mixed2',
	'various','undefined','crap'
]
 
var context = "";
 
for(var i=0,token; (token=tokens[i]); i++) //unsafe code !!
{
	switch(token)
	{
		case 'distinct1': context = do1(); break;
		case 'distinct2': context = do2(); break;
		case 'distinct3': context = do3(); break;
		case 'mixed1':
		case 'mixed2': context = doMix(); break;
		default:
			if(token == 'various'){
				context = doVar();
			}else if(token == 'undefined'){
				context = doUndef();
			}else if(token == 'crap'){
				context = doCrap();
			}else{
				//somethingElse()
			}
			break;
	}
}

which performs REALLY good, and carries the context throughout the switch selector…

ofcause you could upgrade the lookup to take the context on call:

 
function doX(context){ return context; }
function doY(context){ return context; }
function doN(context){ return context; }
 
var cases = {
    1: doX,
    2: doY,
    3: doN
};
 
if (cases[something]) {
    context = cases[something](context);
}

but wouldn’t perform as good as the switch-case because of the copy of context in each call..

]]>
By: Antonio Max https://j11y.io/javascript/how-to-avoid-switch-case-syndrome/#comment-1079 Tue, 21 Jul 2009 14:26:47 +0000 https://j11y.io/?p=989#comment-1079 Yeah! Lets Re-invent the wheel!
The switch is much more elegant than if/else. Also, it haves a default statement, witch provides more security on web apps.
There’s a reason for it to be there.
That’s a nice approach the one you wrote, but its only useful on some very specific situations.
BTW, I think standards are a nice way to share code among other developers and other coders who might have to mess up with your code and will not need to ‘translate’ your logic.

]]>
By: David https://j11y.io/javascript/how-to-avoid-switch-case-syndrome/#comment-1078 Tue, 21 Jul 2009 08:06:24 +0000 https://j11y.io/?p=989#comment-1078 @Dusan – Very interesting article, thanx for the link! With a quick hack to allow single or array alternatives, the “cond” function that DBJ defines could be made to accomodate Kzz’ example above:

function cond( v ) {
  var i;
  for (i=1 ; i < arguments.length-1; i+=2 ) {
  	var vals = typeof arguments[i] == "object" ? arguments[i] : [arguments[i]];
	for (var j = 0; j<vals.length; j++)
	  if (v===vals[j]) 
	    return arguments[i + 1];
  }
  return arguments[i];
}

Fallthrough could now be emulated giving an array for some values:

cond(x,2,"green",[3,4,5],"yellow","defaultclr");

And kzz conditional bit could be done like so:

cond(true,x<2,"green",x<7,"red","defaultclr");

Finally, James’ original function lookup example (although missing the defined check):

cond(something,1,doX,2,doY,3,doN)();

Quite cute, I think! Although, as DBJ writes in his article, the actual value is obviously debatable.

…argh, sorry about the messed-up > and < ! James, help, how do I prevent that?

]]>
By: Dusan https://j11y.io/javascript/how-to-avoid-switch-case-syndrome/#comment-1077 Thu, 16 Jul 2009 23:35:08 +0000 https://j11y.io/?p=989#comment-1077 http://dbj.org/dbj/?p=119

I think you might find this an interesting angle on the same theme …

–DBJ

]]>
By: kzz https://j11y.io/javascript/how-to-avoid-switch-case-syndrome/#comment-1076 Wed, 15 Jul 2009 04:06:14 +0000 https://j11y.io/?p=989#comment-1076 Great!
But,how to transfer this to your method?

switch(i){
  case i < 0:
    alert(' 0;
    alert('>0');break;
  default:
    alert('undefine');break;
}
]]>
By: Haim Michael https://j11y.io/javascript/how-to-avoid-switch-case-syndrome/#comment-1075 Tue, 07 Jul 2009 09:27:12 +0000 https://j11y.io/?p=989#comment-1075 I strongly recommend on learning the alternatives using object oriented code… not sure all of them will apply for JavaScript… though they will defently be relevant for PHP, Java & C#. Best, Haim.

]]>
By: kangax https://j11y.io/javascript/how-to-avoid-switch-case-syndrome/#comment-1074 Mon, 06 Jul 2009 16:34:24 +0000 https://j11y.io/?p=989#comment-1074 It’s a good idea to mention that Javascript objects are quite lousy at emulating proper hash tables, due to their prototypical nature and inability to modify their internal prototype chains (non-standard implementations aside).

A popular example is probably “toString”/”valueOf” keys which, when accessed on a plain object, resolve to `Object.prototype.toString/valueOf` respectively. Keys, matching other `Object.prototype.*` properties (either built-in or user-defined) have similar outcome.

Explicitly modifying keys before property access usually solves this “problem” nicely, albeit in expense of additional overhead. Other solutions, such as `hasOwnProperty`, are either not widely supported (e.g. Safari 2 lacks it) or are not reliable (e.g. `hasOwnProperty(‘__proto__’)` is `true` on plain objects in Gecko-based browsers).

]]>
By: James https://j11y.io/javascript/how-to-avoid-switch-case-syndrome/#comment-1073 Sun, 05 Jul 2009 15:30:11 +0000 https://j11y.io/?p=989#comment-1073 @A, thanks for taking the time to write your comment. I understand that my proposal, and generally the idea of lookup tables may not easily compare to the speed of native switch statements but I still think that using objects to store conditions is cleaner and can be the better solution in certain situations.

Plus, web programming cannot really be prepared to any other type of programming (like “Real time airplane safety”). The basic principles may still hold true but there is a much higher demand for code customization on the web. Storing conditions extends this principle; it allows you and other contributors to change/debug conditions without having to go digging through the source looking through line after line of cases.

Speed/performance, especially when operating at such a high abstraction layer, is largely moot. I understand that we still need to take these things into consideration but today, right now, I consider readability and general code maintainability to be a much higher priority. The question of whether the syntax is cleaner is subjective and therefore really isn’t worth mentioning.

@unscriptable, another way:

var focusMethod = {
    1: function(){ input1.focus(); },
    2: function(){ input2.focus(); },
    3: function(){ input3.focus(); }
};

Multiple return paths may annoy you, but this is even worse IMO:

function something() {
 
    var retValue;
 
    if (true) {
        retValue = 123;
    } else {
        if (true) {
            retValue = 567;
        } else {
            retValue = 234;
        }
    }
 
    return retValue;
}

I know, I know, it’s subjective, but I just really hate this… It looks like the author wanted to follow the “single entry, single exit” rule regardless of what was practical. What’s so bad about multiple return paths anyway? – sure, over-usage is ugly, but if used wisely it’s not that bad IMO.

]]>