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
The Boolean Expression need not be kept in an if-else block, the output of the boolean expression could have easily been returned as
A more advanced form of this problem was using a ternary operator -
Yes, the ternary operator is absolutely unnecessary here.
This one was really funny!
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
There is no need to create a new instance here, you could just write -
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