Issue
I have this chain of switch-cases
switch(something){
case Case1:
validate();
doSomething1();
break;
case Case2:
validate();
doSomething2();
break;
case Case3:
validate();
doSomething3();
break;
case Case4:
validate();
doSomething4();
break;
case Case5:
validate();
doSomething5();
break;
default:
handleDefault();
}
Now in a different place I want these exact switch-cases and default code but I need to add one extra case. What would be a nice way to achieve this so that I don't just have to duplicate all these cases in a different place.
Solution
Perhaps you should use two functions for implementing the concept.
Let's say that we have a function called mainSwitchFunction(int case):
public void mainSwitchFunction(int case){
switch(something){
case Case1:
validate();
doSomething1();
case Case2:
validate();
doSomething2();
case Case3:
validate();
doSomething3();
case Case4:
validate();
doSomething4();
case Case5:
validate();
doSomething5();
default:
handleDefault();
}
}
In normal situations you can use the same function just by calling it.
However, if you want to extend the switch case up to some other cases, you simply define another method let's say extensionOfSwitch(int case2).
public void extensionOfSwitch(int case2){
//call the original switch case function
mainSwitchFunction(case2);
//define another switch statement based on ur case condition.
switch(case2){
case:...
}
/*
this way all the cases will be handled.
*/
}
Answered By - Sayed Hussainullah Sadat