Comparing ONE value with MANY others


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

Java:
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

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


PowerBuilder developers can also utilize the iin() function.

In SQL, use the IN construction instead of multiple OR operators, if possible.

For example, you want to find all the employees which have the first, the middle or the last name "John" (yes, it can be a last name too, like one great English singer!).

*** BAD code: ***

Code: Select all
SELECT * FROM emp WHERE first_name = 'John' OR middle_name = 'John' OR last_name = 'John'


*** GOOD code: ***

Code: Select all
SELECT * FROM emp WHERE 'John' IN (first_name, middle_name, last_name)
User avatar
Ursego
Site Admin
 
Posts: 142
Joined: 19 Feb 2013, 20:33



IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:




cron
Traffic Counter

free counters

eXTReMe Tracker