Comparing ONE value with MANY others

Share this topic:



Link to this posting

Postby Ursego » 21 Feb 2013, 21:51

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.
User avatar
Ursego
Site Admin
 
Posts: 112
Joined: 19 Feb 2013, 20:33

Return to Intriguing World of Logic

Who is online

Users browsing this forum: No registered users and 1 guest


Comparing ONE value with MANY others

Share this topic:


If you think that this site is not too bad, please LIKE it in Facebook. Thanks!





free counters

eXTReMe Tracker