Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Visual Basic
Expertise: Beginner
Aug 8, 1997

Eliminating the If Statement Wherever Possible

If you have to assign True or False to a variable after testing a certain condition, then the If statement may be done away with altogether.

For example, if you have something like this:

 
If (age < 13 and sex = "M") or (age > _
        14 and sex = "F") then FetchRecord _
        = true




it can be replaced by:

 
FetchRecord = (age < 13 and sex = "M") _
        or (age > 14 and sex = "F")




This performs the same function as the If statement above. The FetchRecord variable is correctly assigned True or False. The advantage is that it allows the splitting condition-part of the If statement (see example below). Further, if you like replacing your If statements by IIf, then you know that IIf requires you to add msainfx.dll to your projects in VB3. The above version doesn't.

If the condition-part of if statement is very lengthy, then the above technique allows you to split it. Thus, if you have something like this in VB3:

 
If (Age > 25 and Category = "M1") or _
        (Age > 35 and Category <> "C1") or _
        (Age > 45 and Category = "M7") or _
        (Age > 45 and Category = "P1") then
ProcessRecord
Endif




you can do this:

 
Dim Result as integer
Result = (Age > 25 and Category = "M") _
        or (Age > 35 and Category <> "C1")
Result = Result or (Age > 45 and _
        Category = "M7") or (Age > 45 and _
        Category = "P1")
if Result then ProcessRecord




The advantage is that it allows limited splitting of lines in VB3, thus making the code more readable.

By the way, the technique:

 
x = (y op z) 





to assign True or False to x works in C, Pascal and FoxPro as well. Remember to use = for assignment in Pascal and == for testing in C.

Jaspreet Singh
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date