Reputation: 273
I have a method calculate(some params)
having if-elseif-else
conditions. For each condition I have some statements common to the others. I dont want to rewrite those lines. Is there any way to recall these lines like making a method of those lines within the calculate
method?
calculate(some params){
if(condition1){
specific tast 1 ;
specific tast 2 ;
common task ;
}else if(condtion2){
specific tast 3 ;
specific tast 4 ;
common task ;
}else if(condition3){
specific tast 5 ;
specific tast 6 ;
}else{
specific tast 7 ;
specific tast 8 ;
common task ;
}
}
NOTE : Common task is not for every block.
Upvotes: 0
Views: 539
Reputation: 8715
Just pull your common task ;
down like this:
calculate(some params){
boolean doCommonTask = true;
if(condition1){
specific tast 1 ;
specific tast 2 ;
}else if(condtion2){
specific tast 3 ;
specific tast 4 ;
}else if(condition3){
specific tast 5 ;
specific tast 6 ;
doCommonTask = false; // Skip common task
}else{
specific tast 1 ;
specific tast 2 ;
}
if (doCommonTask) {
common task ;
}
}
Upvotes: 2
Reputation: 2809
In Java there is no possibility to declared local sub-scoped method within a method (unless you do some nasty trick with a inner class).
The closest you can get is to declare a private method on the same class with those commont statements.
Alternatively if it is just a few statements and include them in the original method does not make it too large (thus less readable) then you can simply put them either before the if-else-if ... -else block or after it these can be grouped at the beginning or the end of all blocks.
Upvotes: 0