best practices - multiple functions vs single function with switch case
- by Amit
I have a situation where I need to perform several small (but similar) tasks. I can think of two ways to achieve this.
First Approach:
function doTask1();
function doTask2();
function doTask3();
function doTask4();
Second Approach:
// TASK1, TASK2, ... TASK4 are all constants
function doTask(TASK) {
switch(TASK) {
case TASK1:
// do task1
break;
case TASK2:
// do task2
break;
case TASK3:
// do task3
break;
case TASK4:
// do task4
break;
}
}
A few more tasks may be added in future (though the chances are rare. but this cannot be ruled out)
Please suggest which of the two approaches (or if any other) is a best practice in such a situation.