站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题审查Java代码的十一种常见错误

审查Java代码的十一种常见错误

摘要: 在这篇文章中,我列出了11个Java编程中常见的错误。你可以把这些错误添加到你的代码审查的检查列表(checklist)中
  代码审查是消灭Bug最重要的方法之一,这些审查在大多数时候都特别奏效。由于代码审查本身所针对的对象,就是俯瞰整个代码在测试过程中的问题和Bug。并且,代码审查对消除一些特别细节的错误大有裨益,尤其是那些能够容易在阅读代码的时候发现的错误,这些错误往往不容易通过机器上的测试识别出来。本文就常见的Java代码中容易出现的问题提出一些建设性建议,以便您在审查代码的过程中注意到这些常见的细节性错误。

  通常给别人的工作挑错要比找自己的错容易些。别样视角的存在也解释了为什么作者需要编辑,而运动员需要教练的原因。不仅不应当拒绝别人的批评,我们应该欢迎别人来发现并指出我们的编程工作中的不足之处,我们会受益匪浅的。  正规的代码审查(code inspection)是提高代码质量的最强大的技术之一,代码审查—由同事们寻找代码中的错误—所发现的错误与在测试中所发现的错误不同,因此两者的关系是互补的,而非竞争的。

  如果审查者能够有意识地寻找特定的错误,而不是靠漫无目的的浏览代码来发现错误,那么代码审查的效果会事半功倍。在这篇文章中,我列出了11个Java编程中常见的错误。你可以把这些错误添加到你的代码审查的检查列表(checklist)中,这样在经过代码审查后,你可以确信你的代码中不再存在这类错误了。

  一、常见错误1# :多次拷贝字符串

  测试所不能发现的一个错误是生成不可变(immutable)对象的多份拷贝。不可变对象是不可改变的,因此不需要拷贝它。最常用的不可变对象是String。

  如果你必须改变一个String对象的内容,你应该使用StringBuffer。下面的代码会正常工作:

<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1> <tr> <td>String s = new String ("Text here"); </td></tr></table>
  但是,这段代码性能差,而且没有必要这么复杂。你还可以用以下的方式来重写上面的代码:

<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1> <tr> <td>String temp = "Text here";
String s = new String (temp); </td></tr></table>
  但是这段代码包含额外的String,并非完全必要。更好的代码为:

<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1> <tr> <td>String s = "Text here"; </td></tr></table>
  二、常见错误2#: 没有克隆(clone)返回的对象

  封装(encapsulation)是面向对象编程的重要概念。不幸的是,Java为不小心打破封装提供了方便——Java允许返回私有数据的引用(reference)。下面的代码揭示了这一点:

<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1> <tr> <td>import java.awt.Dimension;
/***Example class.The x and y values should never*be negative.*/
public class Example{
  private Dimension d = new Dimension (0, 0);
  public Example (){ }

  /*** Set height and width. Both height and width must be nonnegative * or an exception is thrown.*/
  public synchronized void setValues (int height,int width) throws IllegalArgumentException{
   if (height < 0 || width < 0)
    throw new IllegalArgumentException();
    d.height = height;
   d.width = width;
  }

  public synchronized Dimension getValues(){
   // Ooops! Breaks encapsulation
   return d;
  }
} </td></tr></table>
  Example类保证了它所存储的height和width值永远非负数,试图使用setValues()方法来设置负值会触发异常。不幸的是,由于getValues()返回d的引用,而不是d的拷贝,你可以编写如下的破坏性代码:

<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1> <tr> <td>Example ex = new Example();
Dimension d = ex.getValues();
d.height = -5;
d.width = -10; </td></tr></table>
  现在,Example对象拥有负值了!如果getValues() 的调用者永远也不设置返回的Dimension对象的width 和height值,那么仅凭测试是不可能检测到这类的错误。

  不幸的是,随着时间的推移,客户代码可能会改变返回的Dimension对象的值,这个时候,追寻错误的根源是件枯燥且费时的事情,尤其是在多线程环境中。

  更好的方式是让getValues()返回拷贝:

<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1> <tr> <td>public synchronized Dimension getValues(){
return new Dimension (d.x, d.y);
} </td></tr></table>
  现在,Example对象的内部状态就安全了。调用者可以根据需要改变它所得到的拷贝的状态,但是要修改Example对象的内部状态,必须通过setValues()才可以。

  三、常见错误3#:不必要的克隆

  我们现在知道了get方法应该返回内部数据对象的拷贝,而不是引用。但是,事情没有绝对:

<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1> <tr> <td>/*** Example class.The value should never * be negative.*/
public class Example{
  private Integer i = new Integer (0);
  public Example (){ }

  /*** Set x. x must be nonnegative* or an exception will be thrown*/
  public synchronized void setValues (int x) throws IllegalArgumentException{
   if (x < 0)
    throw new IllegalArgumentException();
    i = new Integer (x);
  }

  public synchronized Integer getValue(){
   // We can’t clone Integers so we makea copy this way.
   return new Integer (i.intValue());
  }
} </td></tr></table>
  这段代码是安全的,但是就象在错误1#那样,又作了多余的工作。Integer对象,就象String对象那样,一旦被创建就是不可变的。因此,返回内部Integer对象,而不是它的拷贝,也是安全的。

  方法getValue()应该被写为:

<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1> <tr> <td>public synchronized Integer getValue(){
// ’i’ is immutable, so it is safe to return it instead of a copy.
return i;
} </td></tr></table>
  Java程序比C++程序包含更多的不可变对象。JDK 所提供的若干不可变类包括:

  ·Boolean
   ·Byte
   ·Character
   ·Class
   ·Double
   ·Float
   ·Integer
   ·Long
   ·Short
   ·String
   ·大部分的Exception的子类

  四、常见错误4# :自编代码来拷贝数组

  Java允许你克隆数组,但是开发者通常会错误地编写如下的代码,问题在于如下的循环用三行做的事情,如果采用Object的clone方法用一行就可以完成:

<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1> <tr> <td>public class Example{
  private int[] copy;
  /*** Save a copy of ’data’. ’data’ cannot be null.*/
  public void saveCopy (int[] data){
   copy = new int[data.length];
   for (int i = 0; i < copy.length; ++i)
    copy[i] = data[i];
  }
} </td></tr></table>
  这段代码是正确的,但却不必要地复杂。saveCopy()的一个更好的实现是:

<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1> <tr> <td>void saveCopy (int[] data){
  try{
   copy = (int[])data.clone();
  }catch (CloneNotSupportedException e){
   // Can’t get here.
  }
} </td></tr></table>
  如果你经常克隆数组,编写如下的一个工具方法会是个好主意:

<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1> <tr> <td>static int[] cloneArray (int[] data){
  try{
   return(int[])data.clone();
  }catch(CloneNotSupportedException e){
   // Can’t get here.
  }
} </td></tr></table>
  这样的话,我们的saveCopy看起来就更简洁了:

<table borderColor=#cccccc width="90%" align=center bgColor=#e7e9e9 border=1> <tr> <td>void saveCopy (int[] data){
  copy = cloneArray ( data);
} </td></tr></table>

↑返回目录
前一篇: Java 理论与实践: 用JMX检测应用程序
后一篇: SWT/JFace入门指南之加速开发