My Blog

Welcome! What is this blog for/What will be blogged here? Well, frankly, only time will tell that ... ;-) The plan is to have stuff like ... what I plan to do/Interesting things that I want to share. My interests and hobbies ... and what I'm doing/not doing for it. Random thoughts/Opinions. Just about anything I feel like writing! have fun!

Thursday, October 21, 2004

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;

0 Comments:

Post a Comment

<< Home