Positive comparison in Boolean expressions

Share this topic:



Link to this posting

Postby Ursego » 21 Feb 2013, 21:42

Comparing values, try to use "equal" instead of "not equal".

*** BAD code: ***

PB:
Code: Select all
if ls_order_status <> n_order_status.CLOSED) then
   [actions for orders which are not closed]
else
   [actions for closed orders]
end if

C#:
Code: Select all
if (orderStatus <> OrderStatuses.Closed)
   {
   [actions for orders which are not closed]
   }
else
   {
   [actions for closed orders]
   }


*** GOOD code: ***

PB:
Code: Select all
if ls_order_status = n_order_status.CLOSED) then
   [actions for closed orders]
else
   [actions for orders which are not closed]
end if

C#:
Code: Select all
if (orderStatus = OrderStatuses.Closed)
   {
   [actions for closed orders]
   }
else
   {
   [actions for orders which are not closed]
   }


This advice is especially important if the value comparison is nested into a Boolean expression:

*** BAD code: ***

PB:
Code: Select all
if ls_order_status <> n_order_status.CLOSED or &
         ls_state <> n_state.MONTANA or &
         ls_day_type <> n_day_type.WEEKEND then
   [actions when order is not closed OR state differs from Montana OR day is not a weekend]
else
   [actions for other cases]
end if

C#:
Code: Select all
if (orderStatus <> OrderStatuses.Closed ||
         state <> States.Montana ||
         dayType <> DayTypes.WeekEnd)
   {
   [actions when order is not closed OR state differs from Montana OR day is not a weekend]
   }
else
   {
   [actions for other cases]
   }


*** GOOD code: ***

PB:
Code: Select all
if ls_order_status = n_order_status.CLOSED and &
         ls_state = n_state.MONTANA and &
         ls_day_type = n_day_type.WEEKEND then
   [actions when order is closed AND state is Montana AND day is a weekend]
else
   [actions for other cases]
end if

C#:
Code: Select all
if (orderStatus = OrderStatuses.Closed &&
         state = States.Montana &&
         dayType = DayTypes.WeekEnd)
   {
   [actions when order is closed AND state is Montana AND day is a weekend]
   }
else
   {
   [actions for other cases]
   }
User avatar
Ursego
Site Admin
 
Posts: 111
Joined: 19 Feb 2013, 20:33

Return to Intriguing World of Logic

Who is online

Users browsing this forum: No registered users and 1 guest


Positive comparison in Boolean expressions

Share this topic:


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





cron
free counters

eXTReMe Tracker