Well, many of us use switch to solve own tasks, but there is another way I would like to show. We can use Object approach to solve our problem and it looks more intelligent from my point of view.
Let me show couple examples
1. Example with switch
function FoodType(food) {
var getfoodtype;
switch(food) {
case 'apple': getfoodtype = 'fruit'; break;
case 'cucumbers': getfoodtype = 'vegetable'; break;
case 'watermelon': getfoodtype = 'strawberry'; break;
default: getfoodtype = 'not recognized';
}
return getfoodtype;
}
var getfoodtype, case, and break, we can avoid them.
2. Example with Object
FoodType {
apple: fruit,
cucumbers: vegetable,
watermelon: strawberry,
GetFoodType: function(type) {
return(this[type] || 'not recognized');
}
}
Ofc there could be cases where Object approach does not work and we have to use switch, but it is alternative, so keep in mind this.
1 comment :
This is good OO vs procedural approach. Elegant and more portable and plays well into higher design patterns. Nice.
Post a Comment