General programming - one way or another, if for clarity

In a situation where a variable can have two different values, and you do something if its one, something else, if it's different, you would just do:

if(myVariable == FIRST_POSSIBLE_VALUE) { ... }
else { ... }

or would you do:

if(myVariable == FIRST_POSSIBLE_VALUE) { ... }
else if (myVariable == SECOND_POSSIBLE_VALUE) { ... }

for clarity, in a situation where the reader may not necessarily be able to say that they are doing the same (but else if does the “unnecessary” expression)? So what would you do? Thanks!

EDIT: In fact, there are much more different options for something like this: trernary operator, if-else, if-elseif, if-elseif-else, -if-else (with assert), switch. Everyone has their own place, but it is difficult to solve.

+3
source share
9 answers

assert?

if (condition1) { ... }
else { assert(condition2); }

.

if (condition1) { ... }
elsif (condition2) { ... }
else { assert(condition3); }

assert , . assert .

+1

, (.. ). , , , , ,

if(color==red){
....
}else{ //our theme only allows for red and yellow, so the color must be yellow.
....
}

, , (, , , , )

-

if(file.is_open==1){
....
}else if(file.is_open==0){
....

}

as is_open , , , 0, , is_open(), .

'else if', , , , 1 'else if', , , (, C )

+7

Else . , , .

: , , else, , , else. else .

+2

if-else , , , else. : .

- , switch, .

Java . - :

if(string.equals("foo")) {
    // first case
} else if(string.equals("bar")) {
    // second case
} else {
    throw IllegalArgumentException(" ... ");
    // or log it
}

, , , .

+2

else .

if(user.IsNew) { } else { /*in this case user.IsNew != true*/ }

, else. .

, () , . , , , , - ( ), . if else, , , .

if(user.SelectedStyle == Styles.Red) {
} else if(user.SelectedStyle == Styles.Basic) {
} else {
 throw new Exception("Not implemented");
}

( Style.Blue) .

+1

. , , .

, switch.

, , . . , .

+1

, , , , , , "n" 0 100, 3 :

if (n >= 0 && n < 30) {
   case1();
} else if (n >=30 && n < 70) {
   case2();
} else if (n >=70 && n < 100) {
   case3();
}

"else"

} else {
   error("n should be between 0 and 100");
}

, else , , C:

} else { // (n >= 70 && n < 100)
   case3();
}

- , , , , , ,

... , , , , , :

if (p == NULL) {
   doSomething();
} else {
   doSomethingElse();
}

... , if, else.

+1

else . , , , , .

, , else if; .

, , . . - , , , .

+1

. , ?

0

Source: https://habr.com/ru/post/1714370/


All Articles