Should I separate special cases from for loop deliberately, or let a for loop handles special cases naturally?

  softwareengineering

Suppose I need to find the last selected index of options according to last selected contents, eg: options : A,B,C,D,E ,last selected option: C, so the last selected index is 2.

There is a special case : If last selected option does not exist in current options (including case that no options), last selected index is 0. The following is 2 styles of implement the function above:

Style 1: use if-else to deliberately separate the special case from for-loop

const OPTION_ARRAY = ['A','B','C','D','E'];
const lastOption = 'C';

let lastSelectedIndex = 0;

if (new Set(OPTION_ARRAY).has(lastOption)) {
    for( ; lastSelectedIndex < OPTION_ARRAY.length; lastSelectedIndex++){
        if (OPTION_ARRAY[lastSelectedIndex] == lastOption){
            break;
        }
    }
}

Style 2 : choose a for loop which can handle my special case naturally

const OPTION_ARRAY = ['A','B','C','D','E'];
const lastOption = 'C';

let lastSelectedIndex = OPTION_ARRAY.length;

for( ; lastSelectedIndex >= 1 && OPTION_ARRAY[lastSelectedIndex] != lastOption; lastSelectedIndex--){
}

To find lastSelectedIndex, which one should I use? I think style 1 has more code but is easier to understand and can remind me there is a special case. Style 2 has less code, but I think it is less straight forward. Should I separate special case from for loop, or let a for loop handles special case naturally?

2

You should write code that is easily understandable. Do simple things, not tricky things. Use existing functionality.

For example, your particular use case is

let lastSelectedIndex = OPTION_ARRAY.indexOf(lastOption);
if (lastSelectedIndex === -1) lastSelectedIndex = 0;

If you were to write the code yourself, you don’t want to do fancy stuff like using the variable you want to fill as an iteration index that sort of happens to come out to the right value. Just use another variable. It’s not like you’re running out of names.

let lastSelectedIndex = 0; // fallback value
for (let i = 0; i < OPTION_ARRAY.length; ++i) {
  if (OPTION_ARRAY[i] === lastOption) {
    lastSelectedIndex = i;
    break;
  }
}

LEAVE A COMMENT