« JUnit Exception Handling | Main | Code Quality »

Java String Tricks

Raible:

if (request.getParameter("checkbox") != null &&
request.getParameter("checkbox").equals("true"))

With StringUtils.equals(String, String), you get a little less coding:

if (StringUtils.equals(
request.getParameter("checkbox"), "true"))

If you're using Struts or some other library that already depends on commons-lang, why wouldn't you use it? Possibly performance reasons, but I doubt it causes much of a hit.

Actually, the latter implementation will perform better. It has half the hash lookups and HotSpot can inline the method invocation. [ crazybob ]

Actually, even easier than that....
 if ("true".equals(request.getParameter("checkbox")))
The string class already does the null check inside of the equals call and requires no exteranl library. I got this from an old C trick where whenever you are comparing somethingto null you put the null on the left side. If you accidentally type an assignment then the compiler will crash because a constant is not a valid LValue for an assignment.

About

This page contains a single entry from the blog posted on January 30, 2003 8:36 AM.

The previous post in this blog was JUnit Exception Handling.

The next post in this blog is Code Quality.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33