Saturday, April 28, 2007

Comparison using Java's ternary operator

When using Java's ternary operator which allows assignment to a variable based upon one or more Boolean decisions, construct the code in such a way as to mitigate null exception errors.

For example, in the event the field “verified” contains a null value, the following construct results in a null exception error:


boolean verifiedAsBoolean = "Y".equalsIgnoreCase(verified) ? true : false;


This version will return false.


boolean verifiedAsBoolean = verified.equalsIgnoreCase("Y") ? true : false;


Although acceptable, consider employing a basic if / then construct. The test example below will not fail if verified contains a null and will return false. The construct also allows new logic to be to implemented more efficiently.

If ('Y'.equals(verified)) {
verifiedAsBoolean = true;
} else {
verifiedAsBoolean = false;
}

No comments: