先看这个JUnit测试:
public void testBoolean(){
assertFalse(Boolean.getBoolean("true"));
}
你认为能够测试通过吗?如果你觉得不能,那就请你亲自去运行一下看看。
......
结果如何?的确能够测试通过!
这行代码我好像是从effective java中看到的(记性不好:P),作者告诫我们读代码不能想当然,主观臆测。
看过Boolean.getBoolean()的注释或是实现之后(注1),其实这个方法与Boolean类并没有想象中的关系。不由内心生出一种被作者耍了的感觉,其实是我们读代码经常主观臆测,渐渐养成了想当然的毛病。
我时常提醒自己不要想当然,不幸的是恶习难改,今天又中招了。为了写测试类的,我需要比较excel文件中的2行的内容是否相等。我通过Apache的poi把excel中的行转化成HSSFRow对象,发现它overide了compareTo方法,大喜,以为又可以偷懒了。马上完成,运行测试,通过,更喜。将2行修改成不一样,运行,还是通过,大惊!检查无误后,不解,查看java doc:
compareTo
public int compareTo(java.lang.Object obj)
Specified by:
compareTo in interface java.lang.Comparable
什么也没有,汗。只好找来源代码,如下:
public int compareTo(Object obj)
{
HSSFRow loc = (HSSFRow) obj;
if (this.getRowNum() == loc.getRowNum())
{
return 0;
}
if (this.getRowNum() < loc.getRowNum())
{
return -1;
}
if (this.getRowNum() > loc.getRowNum())
{
return 1;
}
return -1;
}
顿悟,原来只是比较行号是否相等而已。
也许是过于有规律的生活方式影响到了我们的思维方式,然而,作为一名程序员,我们要有敏锐的头脑和发散的思维。所以不敢耽误,马上写到blog上来,时时刻刻提醒我和看到这篇文章的人编程千万不可想当然哦。
注1:
/**
* Returns true if and only if the system property named
* by the argument exists and is equal to the string "true".
* (Beginning with version 1.0.2 of the JavaTM platform,
* the test of this string is case insensitive.)
* A system property is accessible through getProperty,
* a method defined by the System class.
* If there is no property with the specified name, or if
* the specified name is empty or null, then false is returned.
*/
public static boolean getBoolean(String name) {
boolean result = false;
try {
result = toBoolean(System.getProperty(name));
} catch (IllegalArgumentException e) {
} catch (NullPointerException e) {
}
return result;
}
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}