devxlogo

Eliminating the If Statement Wherever Possible

Eliminating the If Statement Wherever Possible

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

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. TheFetchRecord variable is correctly assigned True or False. Theadvantage is that it allows the splitting condition-part of theIf statement (see example below). Further, if you like replacingyour If statements by IIf, then you know that IIf requires youto add msainfx.dll to your projects in VB3. The above versiondoesn’t.

If the condition-part of if statement is very lengthy, then theabove technique allows you to split it. Thus, if you have somethinglike 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") thenProcessRecordEndif

you can do this:

 Dim Result as integerResult = (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 inVB3, 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 aswell. Remember to use = for assignment in Pascal and == for testingin C.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist