Page 1 of 1

Positive comparison in Boolean expressions

PostPosted: 21 Feb 2013, 21:42
by Ursego
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]
   }