Logo

Programming-Idioms

  • VB
  • Js

Idiom #131 Successive conditions

Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true.
Don't evaluate a condition when a previous condition was true.

c1 ? f1 : c2 ? f2 : f3

The ternary operator is great for conciseness and statement-freedom.
It's not so great for clarity.
Oh well. \(^w^)/
if (c1) {
  f1();
} else if (c2) {
  f2();
} else if (c3) {
  f3();
}

Using if/else
switch (true) {
  case c1:
    f1();
    break;
  case c2:
    f2();
    break;
  case c3:
    f3();
    break;
}

Using switch/case
If c1 Then
    f1()
ElseIf c2 Then
    f2()
else c3 Then
    f3()
End If
if c1 then
    f1;
elsif c2 then
    f2;
elsif c3 then
    f3;
end if;

assume that f, g, and h are procedure and that a and b are Boolean

New implementation...
< >
programming-idioms.org