This is a thing I'm doing a lot lately.
Example:
setCircle(circle, i, { current }) {
if (i == current) {
circle.src = 'images/25CE.svg'
circle.alt = 'Now picking'
} else if (i < current) {
circle.src = 'images/25C9.svg'
circle.alt = 'Pick failed'
} else if (i > current) {
circle.src = 'images/25CB.svg'
circle.alt = 'Pick chance'
}
}
Oftentimes the if/else ladder is significantly more complicated than this...
See the final clause? It is redundant. The ladder is supposed to ultimately catch all possible conditions. Thus it could be rewritten like that:
setCircle(circle, i, { current }) {
if (i == current) {
circle.src = 'images/25CE.svg'
circle.alt = 'Now picking'
} else if (i < current) {
circle.src = 'images/25C9.svg'
circle.alt = 'Pick failed'
} else {
circle.src = 'images/25CB.svg'
circle.alt = 'Pick chance'
}
}
This is how I used to write code, but I dislike this style. My complaint is that the condition under which the last part of code will be executed is not obvious from the code. I thus started writing this condition explicitly to make it more evident.
However:
- Explicitly writing the final exhaustive condition is my own idea, and I have bad experiences with my own ideas - usually people scream at me about how horrible what I'm doing is - and (sometimes much) later on I find out that it was indeed suboptimal;
- One hint why this may be a bad idea: Not applicable to Javascript, but in other languages, compilers tend to issue warnings or even errors about control reaching end of function. Hinting doing something like that might be not too popular or I'm doing it wrong.
- Compiler complaints made me sometimes write the final condition in a comment, but I guess doing so is horrible since comments, unlike code, have no effect on actual program semantics:
} else { // i > current
circle.src = 'images/25CB.svg'
circle.alt = 'Pick chance'
}
Am I missing something? Or is it OK to do what I described or is it a bad idea?