Positive comparison in Boolean expressions


Link to this posting

Postby Ursego » 21 Feb 2013, 21:42

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).
User avatar
Ursego
Site Admin
 
Posts: 143
Joined: 19 Feb 2013, 20:33



Ketones are a more high-octane fuel for your brain than glucose. Become a biohacker and upgrade yourself to version 2.0!



cron
Traffic Counter

eXTReMe Tracker