Alex headshot

AlBlue’s Blog

Macs, Modularity and More

String comparisons

2004 Java

There are many times when you want to do one of a set of actions based on the contents of a string. It happens a lot in web-based applications, where there is some kind of parameter (e.g. command=postNewBlog) in the HTTP request that kicks of a specific bit of the application. [Struts does something similar to link its actions with the URLs; but it uses the URL path as opposed to an additional parameter; and it uses the Command pattern to do the dispatching, but that's outside the scope of this post.]

One way of handling the action is to use a number of if statements:

if (command.equals("postNewBlog")) {
  // do blog action
} else if (command.equals("preview")) {
  // do preview action
} ...

Of course, you also have to test for other conditions, such as whether command is null, and whether the user is logged in first.

In any case, you can avoid the dreaded NullPointerException simply by swapping the order of the comparisons. Instead of doing expr.equals(literal), just do them the other way around: literal.equals(expr). It might look a bit odd, but then you don't need to test for null any more, since a literal can never be null:

if ("postNewBlog".equals(command)) {
  // do blog action
} else if ("preview".equals(command)) {
  // do preview action
} ...

Might look a bit odd at first, but it's safer.