문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top