samedi 21 août 2021

What is the most graceful way to write unreachable else block

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?

Aucun commentaire:

Enregistrer un commentaire