Page 1 of 1

Comparing ONE value with MANY others

PostPosted: 21 Feb 2013, 21:51
by Ursego
Comparing one value with many other values, use the switch/choose case construction instead of multiple ||/OR operators, so the compared value is mentioned in the code only once.

In this situation, we are not really switching/choosing between options (so we can call it "a fake switch/choose"), but why not to do our code more readable if the programming language doesn't allow the IN clause like T-SQL and PL/SQL do?

*** BAD code: ***

PB:
Code: Select all
if ls_city = "Toronto" or ls_city = "Boston" or ls_city = "Chicago" then
   ls_message = "Nice city!"
end if

C#:
Code: Select all
if (city == "Toronto" || city == "Boston" || city == "Chicago")
{
   message = "Nice city!";
}


*** GOOD code: ***

PB:
Code: Select all
choose case ls_city
case "Toronto", "Boston", "Chicago"
   ls_message = "Nice city!"
end choose

C#:
Code: Select all
switch (city)
{
   case "Toronto":
   case "Boston":
   case "Chicago":
      message = "Nice city!";
      break;
}


PowerBuilder developers can also utilize the iin() function.