velocity-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Shinobu Kawai <shinobu.ka...@gmail.com>
Subject [FAQ] How do you check for null?
Date Fri, 03 Dec 2004 04:21:45 GMT

Hi all,

I thought it's about time the null question go to the FAQ.  I'm trying
to thinking of a way to summarize it.


Problem: I want to check for null, something like this:
    #if ($car.fuel == null)


Approach 1: Use the fact that null is evaluated as a false conditional.
  cf. http://jakarta.apache.org/velocity/user-guide.html#Conditionals
    #if( ! $car.fuel )

Note : The conditional will also pass if the result of $car.fuel is
the boolean false.  What this approach is actually checking is whether the
reference is null or false.


Approach 2: Use the fact that null is quiet references.
  cf. http://jakarta.apache.org/velocity/user-guide.html#Quiet%20Reference%20Notation
    #if( "$!car.fuel" == "" )

Note : The conditional will also pass if the result of $car.fuel is a
blank String.  What this approach is actually checking is whether the reference
is null or blank.
BTW, just checking for blank can be achieved by:
    #if( "$car.fuel" == "" )


Approach 3: Using a Tool.
  cf. http://wiki.apache.org/jakarta-velocity/NullTool
    #if( $null.isNull($car.fuel) )

Note : Of course, NullTool must be in the Context as "null" in this case.


Approach 4: Don't check for null directly, use a self-explaining method.
    #if( $car.isFuelEmpty() )

Note : My recommended solution.  You have to implement the method, but
it makes the template so easy-to-read.


Any comments/suggestions to make it more understandable are welcome.

Best regards,
-- Shinobu Kawai

--
Shinobu Kawai <shinobu.kawai@gmail.com >




---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org


Mime
View raw message