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: ***

Code: Select all
if (orderStatus != OrderStatus.CLOSED) {
   [actions for orders which are not closed]
} else {
   [actions for closed orders]
}

*** GOOD code: ***

Code: Select all
if (orderStatus == OrderStatus.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: ***

Code: Select all
if (orderStatus != OrderStatus.CLOSED || state != States.MONTANA || dayType != DayType.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: ***

Code: Select all
if (orderStatus == OrderStatus.CLOSED && state == States.MONTANA && dayType == DayType.WEEKEND) {
   [actions when order is closed AND state is Montana AND day is a weekend]
} else {
   [actions for other cases]
}

Don't forget to use AND (&&) instead of OR (||)! :lol:

Anyway, it's better to evaluate the expression in advance, store its result in a Boolean variable with a quality, descriptive name, and use that variable in the if statement (see Short conditions in IFs).