现在的位置: 首页 > 综合 > 正文

你写的代码真的对吗?

2013年10月17日 ⁄ 综合 ⁄ 共 1465字 ⁄ 字号 评论关闭

俗话说,文无第一,武无第二,作为程序员,也很难比出高低,但是代码的质量去可以让人一眼看出水平的高低,有些代码不仅仅是质量不好,运行效率低,甚至在一些情况下会导致系统的错误。

还记得几年前,项目经理发信说过,需要做defense coding,就是预防代码发生不可预见的错误。那么让我们来看看一下代码的区别。

代码范例1:

String configurationName = "BackDoor";

String configureValue = getConfigurationValue(configuratoionName);

if(configurationValue.equals("BackDoorDirty")){

//Let's do some dirty things

}

这段代码可以写的更好一些吗?

答案是肯定的,应该有不少人知道,name 和 value应该定义为一个常量。

final static String configurationName = "BackDoor";

final static String DIRTY_BACKDOOR = "DirtyBackDoor";

String configureValue = getConfigurationValue(configuratoionName);

if(configurationValue.equals(DIRTY_BACKDOOR)){

//Let's do some dirty things

}

这样一来至少在其他的地方需要做dirty things的时候,不需要重新定义name 和value的值,同时也不会担心因为拼写的错误导致程序不能正常运行,那么这样写真的对吗?会有问题吗,肯定会有的。

因为getConfigurationValue(configuratoionName),这个方法无法保证返回以个值,这个方法可能是第三方提供的方法,也可能是自己的代码,要保证configurationValue.equals(DIRTY_BACKDOOR)可以正常运行的前提是,他不会返回一个null值。看来我们需要把代码改称

final static String configurationName = "BackDoor";

final static String DIRTY_BACKDOOR = "DirtyBackDoor";

String configureValue = getConfigurationValue(configuratoionName);

if(configureValue!=null && configurationValue.equals(DIRTY_BACKDOOR)){

//Let's do some dirty things

}

这样就做到了我前面提到的defense coding,这样写的确对了,但是并不是很好的代码习惯,让我们看看以下的代码如何:

final static String configurationName = "BackDoor";

final static String DIRTY_BACKDOOR = "DirtyBackDoor";

String configureValue = getConfigurationValue(configuratoionName);

if(DIRTY_BACKDOOR.equals(configurationValue)){

//Let's do some dirty things

}

这样一来,我们既不需要去做那个null的检查,也完全可以避免configurationValue是null造成的异常。

抱歉!评论已关闭.