Is there a standard structured programming pattern for avoiding repetition in cases like the following (illustrated in C)?
if(/* … */) process(foo,bar,baz,0);
else if(/* … */) process(foo,bar,baz,2);
else if(/* … */) process(foo,bar,baz,5);
/* else don’t process() */
Storing the varying value in a variable and making the call later is the obvious approach, but requires skipping the call in the final case, which can be accomplished in several clumsy fashions:
Extra flag variable
int arg;
bool go=true;
if(/* … */) arg=0;
else if(/* … */) arg=2;
else if(/* … */) arg=5;
else go=false;
if(go) process(foo,bar,baz,arg);
Invalid value (if one exists)
int arg=-1;
if(/* … */) arg=0;
else if(/* … */) arg=2;
else if(/* … */) arg=5;
if(arg>=0) process(foo,bar,baz,arg);
Meaningless loop
do {
int arg;
if(/* … */) arg=0;
else if(/* … */) arg=2;
else if(/* … */) arg=5;
else break;
if(go) process(foo,bar,baz,arg);
} while(false);
Redundant test
int arg;
if(/* … */) arg=0;
else if(/* … */) arg=2;
else if(/* … */) arg=5;
if(/* … */ || /* … */ || /* … */)
process(foo,bar,baz,arg);
Unspeakable evil
int arg;
if(/* … */) arg=0;
else if(/* … */) arg=2;
else if(/* … */) arg=5;
else goto skip;
process(foo,bar,baz,arg);
skip:;
Is there a better, broadly-applicable option? Python’s else on loops comes to mind, but can’t very well be put on an if! (Python also addresses this particular case with functools.partial, but that doesn’t apply to statements.)
Aucun commentaire:
Enregistrer un commentaire