Please use Boolean.getBoolean(SOME_FLAG_KEY)

Boolean.getBoolean(String) is one of the most useful convenience methods.  It gets the boolean flag in system properties by the name.  But it has not been used as widely as it should be.  Oftentimes I see code (recently written, not legacy code) like this:

String flag1 = System.getProperty(FLAG_ONE_KEY);
String flag2 = System.getProperty(FLAG_TWO_KEY);
if((flag1 != null && "true".equalsIgnoreCase(flag1)) ||
    (flag2 != null && "true".equalsIgnoreCase(flag2))) {
    //ok, do something special for this condition
}

Another wheel is reinvented with a lot of typing, while this could be as simple as this:

if(Boolean.getBoolean(FLAG_ONE_KEY) || Boolean.getBoolean(FLAG_ONE_KEY)) {
    //ok, do something special for this condition
}

This method is in JDK as early as 1.0.  If such a good one got ignored by so many for so long, we can hardly blame users.  After all, an object-oriented mind wouldn't expect Boolean to retrieve a system property.  If this method had been System.getPropertyAsBoolean(String key), will it be better recognized and utilized?

technorati tags: ,

Comments:

Actually, I've found this method can cause a lot of trouble... See what I wrote about it here.

Posted by ishirav on June 11, 2006 at 11:24 PM EDT #

This method is very badly named. Please do not use it for the sake of clear code. The API doc for this method does explain the proper use, but it is not at all what one would expect. It, and its siblings in other primitive classes, should be deprecated in favor of more appropriate methods in the System class.

While it is true that developers are to blame if they don't check the docs, it is also true that the basic purpose of an API method should be clear from its signature. The docs should clarify the nuances, edge cases, and precise functionality of a method, but its general purpose should be understood without checking the documentation.

I didn't get bit by this bug, I stumbled across it's correct usage in someone else's code and couldn't figure out what they were doing. I've been programming Java for nearly 10 years and have never used it. There's a reason it's not used often: it's in the wrong place and has the wrong name. I would guess that a good percentage of its uses are actually bugs.

Posted by kyle on May 17, 2010 at 03:29 AM EDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

Cheng Fang

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today