Wednesday, June 16, 2010

Caution while using "and" and "or" operator in standard visual snippet

The "and" & “or” operator from standard visual snippet doesn't execute the way it is getting executed in Java. In visual snippet case it does differently

The translated code

java.lang.String __result__1 = null;
input1 = __result__1;
boolean __result__4 = input1.trim().length() != 0;
boolean __result__3 = input1 != null;
boolean __result__5;
{// and
__result__5 = __result__3 && __result__4;
}

In the above snippet the string is null, when using the "and" & “or” operator. It executes the left and right hand side conditions separately and stores in a variable and then does an 'and' operation on the variable.

While executing you will get a null pointer exception, because the string is null on top of that we are trying to trim().length()


The visual snippet operator will unnecessarily execute both the left and right hand side conditions which we don't want to do


To avoid this use the 'and' logical operator '&&' in the visual snippet.

boolean __result__6 = input1 != null && input1.trim().length() != 0;

In this case it executes as it does it in Java the safer way. :-)

0 comments: