Pregunta

I've noticed that style checkers give you a warning when inline conditionals are implemented: "Do not use inline conditionals". Why?

¿Fue útil?

Solución

I think it's because of code readability.

Consider this two codes, where a is a number (int, float, or whatever):

#1

if(a < 0) {
    a = 0;
} else if(a < 10) {
    a = 10;
} else if(a < 20) {
    a = 20;
} else if(a < 30) {
    a = 30;
}

#2

a = a < 0 ? 0 : a < 10 ? 10 : a < 20 ? 20 : a < 30 ? 30 : a;

They do exactly the same thing, but the first one is more clear.

Otros consejos

It takes effort to understand what going around in a inline conditional. If there is only one condition, it is preferred to use the conditional operator. For more that one conditions, if-else-if construct is better due to the ease of readability.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top