Vladdy
03-30-2003, 02:58 PM
I had a flashback from my C++ programming days and thought why not apply it in JavaScript...
Consider a very common task: branching execution based on the value of a string variable.
"Novice" approach:
function processEvent(event)
{ if(event=='dothis') { /* do this */ }
if(event=='dothat') { /* do that */ }
if(event=='domore') { /* do more */ }
}
"Intermediate" approach:
function processEvent(event)
{ switch(event)
{ case 'dothis': /* do this */ break;
case 'dothat': /* do that */ break;
case 'domore': /* do more */ break;
}
}
"Expert" approach (avoiding mile long functions):
function processEvent(event)
{ switch(event)
{ case 'dothis': doThis(); break;
case 'dothat': doThat(); break;
case 'domore': doMore(); break;
}
}
function doThis() { /*do this*/ }
function doThat() { /*do that*/ }
function doMore() { /*do more*/ }
Now, what do you think of:
function processEvent(event)
{ return eventHandlers[event]();
}
var eventHandlers = new Array();
eventHandlers['dothis'] = function { /*do this*/ }
eventHandlers['dothat'] = function { /*do that*/ }
eventHandlers['domore'] = function { /*do more*/ }
:thumbsup:
Consider a very common task: branching execution based on the value of a string variable.
"Novice" approach:
function processEvent(event)
{ if(event=='dothis') { /* do this */ }
if(event=='dothat') { /* do that */ }
if(event=='domore') { /* do more */ }
}
"Intermediate" approach:
function processEvent(event)
{ switch(event)
{ case 'dothis': /* do this */ break;
case 'dothat': /* do that */ break;
case 'domore': /* do more */ break;
}
}
"Expert" approach (avoiding mile long functions):
function processEvent(event)
{ switch(event)
{ case 'dothis': doThis(); break;
case 'dothat': doThat(); break;
case 'domore': doMore(); break;
}
}
function doThis() { /*do this*/ }
function doThat() { /*do that*/ }
function doMore() { /*do more*/ }
Now, what do you think of:
function processEvent(event)
{ return eventHandlers[event]();
}
var eventHandlers = new Array();
eventHandlers['dothis'] = function { /*do this*/ }
eventHandlers['dothat'] = function { /*do that*/ }
eventHandlers['domore'] = function { /*do more*/ }
:thumbsup: