16 Dec 2004 derupe   » (Journeyer)

Java Code: Boolean Fun

Over time I've encountered Java code that I feel could have been written better. I'll list out a few example that I encountered recently.

If you do code review you'll want to check PMD, JLint, FindBugs and some such tools [I've mentioned these before while talking of Eclipse Plugins.]

Boolean Fun

Cosider this code

if(str.length() > len) {
      return true;
} else {
      return false;
The Boolean Expression need not be kept in an if-else block, the output of the boolean expression could have easily been returned as

return (str.length() > len);

A more advanced form of this problem was using a ternary operator -

return (str.length() > len ? true : false);

Yes, the ternary operator is absolutely unnecessary here.

This one was really funny!

if(!(x == y))

I wonder why the developer thought of such a convoluted way to write x != y.

Another common problem I have come across when Boolean objects are used. Invariably you'll see

Boolean b = new Boolean(true);

There is no need to create a new instance here, you could just write -

Boolean b = Boolean.TRUE;

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!