1

For example. (in Pseudo language)

if ( a == 1 || a == 2 || a == 3 ) {
   ... some unrelated pre handling ...
   if (a == 1) {
      ...
   } else if( a == 2) {
      ...
   } else if( a == 3) {
      ...
   } else {
     ///////////// this is the unreachable else branch /////////
   }
   ... some unrelated post handling ...
}

I know I could just turn the last else if into else, but that would be not clear for reviewers.

if ( a == 1 || a == 2 || a == 3 ) {
   ... some unrelated pre handling ...
   if (a == 1) {
      ...
   } else if( a == 2) {
      ...
   } else { // this will be a == 3, but once I change the outer `a == 1 || a == 2 || a == 3` then here may be forgotten to change.
      ...
   }
   ... some unrelated post handling ...
}

Also, I could throw exception in the else block, but seems dumb,

if ( a == 1 || a == 2 || a == 3 ) {
   ... some unrelated pre handling ...
   if (a == 1) {
      ...
   } else if( a == 2) {
      ...
   } else if( a == 3) {
      ...
   } else {
     throw "unexpected case";
   }
   ... some unrelated post handling ...
}

EDIT: using switch ... case ... default does not change much, the default will be the useless branch.

Any better idea?

osexp2000
  • 2,910
  • 30
  • 29
  • I'm not sure about the problem you have. Why do you need to write code which can't be reached? Or is it about catching e.g. invalid input? – Some programmer dude Aug 21 '21 at 07:39
  • @Someprogrammerdude it is not a problem. I could change the last `else if (a==3)` into `else` so that no unreachable branch, but once I do that, when later someone look at the `else` block, to figure out what kind of cases it will be he has to look at the outer `if (a == 1 || a == 2 || a == 3)` to know oh the `else` just means `a==3`, this is not good for reviewers. In other words, an uneasy-to-figure-out `else` is not good, but if I write the `else`, due to the outer `if (a==1||a==2||a==3)`, the `else` become useless, so I'd like to know if there is any elegant way, without throwing exception – osexp2000 Aug 21 '21 at 08:03

1 Answers1

0

Depending on the actual language you, you could use a switxh statement. In that case, the "unreachable" else block would be the default case.

aaronlukacs
  • 389
  • 2
  • 8