Wednesday, September 25, 2013

Alternative to SELECT is IF-ELSEIF

The RPG operation code SELECT as been with us for many years. It is also found in many other languages, including CL (see the post SELECT in CL).

An alternative was introduced in one of the IBM i V5 releases, the IF-ELSEIF operation codes. If the first IF is not true then the first of the ELSEIF is executed, just like the WHEN in the SELECT group.

Below I show two segments of code that do the same thing, on the left column using the SELECT and on the right the IF-ELSEIF:

 select ;
   when (REGCDE = 'ER') ;
     DESC = 'East region' ;
   when (REGCDE = 'WR') ;
     DESC = 'West region' ;
   when (REGCDE = 'CA') ;
     DESC = 'Canada' ;
   other ;
     DESC = 'Unknown' ;
 endsl ;
 if (REGCDE = 'ER') ;
   DESC = 'East region' ;
 elseif (REGCDE = 'WR') ;
   DESC = 'West region' ;
 elseif (REGCDE = 'CA') ;
   DESC = 'Canada' ;
 else ;
   DESC = 'Unknown' ;
 endif ;

Why does he do that?   I always type the names of fields from files in capitals, including display and printer files. All of my work fields are in camel case (mix of upper and lower case). I do this so that someone else looking at my code knows which fields are from files and which are not.
I also put the fields and test in parentheses () for all operations like IF, FOR, DO, WHEN, etc. as I think it makes it easier to tell what goes with what in a complex statement.

As far as I have been able to tell, speedwise, they are the same. I use the IF-ELSEIF just because it takes up one less line in the source member.

Why was the ELSEIF instroduced? Could it be that there is an ELSEIF in PHP and this is part of IBM's way to help move us over to PHP? Or to encourage PHP programmers to try RPG?

You can learn more about the ELSEIF operation code on the IBM website here»

 

This article was written for IBM i 7.1, and it should work with earlier releases too.

2 comments:

  1. I usually go for Select when there are more conditions, say, more than 4 or 5. It's more readable. For 1 or 2 conditions I would go with ElseIf.

    ReplyDelete
  2. i go with select for readability + it's easier to search for it in the source when i need to go over it
    where if + elseif are used more (usually when there are less conditions) and therefore will take me longer to get to that specific code line

    ReplyDelete

To prevent "comment spam" all comments are moderated.
Learn about this website's comments policy here.

Some people have reported that they cannot post a comment using certain computers and browsers. If this is you feel free to use the Contact Form to send me the comment and I will post it for you, please include the title of the post so I know which one to post the comment to.