Don't duplicate conditions in Boolean expressions

Share this topic:



Link to this posting

Postby Ursego » 19 Feb 2013, 22:26

Don't add to a Boolean expression any conditions which don't change the produced result

Foolish advice, you say? Why to add them? But this advice has been born during my code inspection practice. Look at the following nice examples:

Code: Select all
if (not IsNull(ld_expire_date)) and ld_expire_date < ld_today then

is logically the same as

Code: Select all
if ld_expire_date < ld_today then

because when ld_expire_date contains null then the second part of the expression will produce null, and nulls are interpreted by code branching operators as false.

Code: Select all
if dw_xxx.RowCount() > 0 and dw_xxx.GetSelectedRow(0) > 0 then

must be re-written as

Code: Select all
if dw_xxx.GetSelectedRow(0) > 0 then

because when dw_xxx contains no rows, dw_xxx.GetSelectedRow(0) will never return a positive number.

Code: Select all
if (not IsNull(ids_xxx)) and IsValid(ids_xxx) then

is the same as

Code: Select all
if IsValid(ids_xxx) then

because if IsValid returns true (i.e. memory is allocated for the pointed object) then, of course, the variable is pointing something (i.e. is populated), so testing it with IsNull will produce true.

Code: Select all
if ll_row_count > 0 then
       for ll_row = 1 to ll_row_count
              [...]
       next
end if

will work exactly in the same way as simply

Code: Select all
for ll_row = 1 to ll_row_count
       [...]
next
User avatar
Ursego
Site Admin
 
Posts: 112
Joined: 19 Feb 2013, 20:33

Return to Elegant Code

Who is online

Users browsing this forum: No registered users and 1 guest


Don't duplicate conditions in Boolean expressions

Share this topic:


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





free counters

eXTReMe Tracker