背景:#EDF0F5 #FAFBE6 #FFF2E2 #FDE6E0 #F3FFE1 #DAFAF3 #EAEAEF 默認(rèn)  
閱讀內(nèi)容

審查Java代碼的一些常見(jiàn)錯(cuò)誤

[日期:2008-07-20] 來(lái)源:  作者:九通科技 [字體: ]

代碼審查是消滅Bug最重要的方法之一,這些審查在大多數(shù)時(shí)候都特別奏效。由于代碼審查本身所針對(duì)的對(duì)象,就是俯瞰整個(gè)代碼在測(cè)試過(guò)程中的問(wèn)題和Bug。并且,代碼審查對(duì)消除一些特別細(xì)節(jié)的錯(cuò)誤大有裨益,尤其是那些能夠容易在閱讀代碼的時(shí)候發(fā)現(xiàn)的錯(cuò)誤,這些錯(cuò)誤往往不容易通過(guò)機(jī)器上的測(cè)試識(shí)別出來(lái)。本文就常見(jiàn)的Java代碼中容易出現(xiàn)的問(wèn)題提出一些建設(shè)性建議,以便您在審查代碼的過(guò)程中注意到這些常見(jiàn)的細(xì)節(jié)性錯(cuò)誤。

  通常給別人的工作挑錯(cuò)要比找自己的錯(cuò)容易些。別樣視角的存在也解釋了為什么作者需要編輯,而運(yùn)動(dòng)員需要教練的原因。不僅不應(yīng)當(dāng)拒絕別人的批評(píng),我們應(yīng)該歡迎別人來(lái)發(fā)現(xiàn)并指出我們的編程工作中的不足之處,我們會(huì)受益匪淺的。

 正規(guī)的代碼審查(code inspection)是提高代碼質(zhì)量的最強(qiáng)大的技術(shù)之一,代碼審查—由同事們尋找代碼中的錯(cuò)誤—所發(fā)現(xiàn)的錯(cuò)誤與在測(cè)試中所發(fā)現(xiàn)的錯(cuò)誤不同,因此兩者的關(guān)系是互補(bǔ)的,而非競(jìng)爭(zhēng)的。

  如果審查者能夠有意識(shí)地尋找特定的錯(cuò)誤,而不是靠漫無(wú)目的的瀏覽代碼來(lái)發(fā)現(xiàn)錯(cuò)誤,那么代碼審查的效果會(huì)事半功倍。在這篇文章中,我列出了11個(gè)Java編程中常見(jiàn)的錯(cuò)誤。你可以把這些錯(cuò)誤添加到你的代碼審查的檢查列表(checklist)中,這樣在經(jīng)過(guò)代碼審查后,你可以確信你的代碼中不再存在這類(lèi)錯(cuò)誤了。

  一、常見(jiàn)錯(cuò)誤1# :多次拷貝字符串

  測(cè)試所不能發(fā)現(xiàn)的一個(gè)錯(cuò)誤是生成不可變(immutable)對(duì)象的多份拷貝。不可變對(duì)象是不可改變的,因此不需要拷貝它。最常用的不可變對(duì)象是String。

  如果你必須改變一個(gè)String對(duì)象的內(nèi)容,你應(yīng)該使用StringBuffer。下面的代碼會(huì)正常工作:

String s = new String ("Text here"); 

  但是,這段代碼性能差,而且沒(méi)有必要這么復(fù)雜。你還可以用以下的方式來(lái)重寫(xiě)上面的代碼:

String temp = "Text here"; 
String s = new String (temp); 

  但是這段代碼包含額外的String,并非完全必要。更好的代碼為:

String s = "Text here"; 

  二、常見(jiàn)錯(cuò)誤2#: 沒(méi)有克隆(clone)返回的對(duì)象

  封裝(encapsulation)是面向?qū)ο缶幊痰闹匾拍。不幸的是,Java為不小心打破封裝提供了方便——Java允許返回私有數(shù)據(jù)的引用(reference)。下面的代碼揭示了這一點(diǎn):

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;     }   }   

  Example類(lèi)保證了它所存儲(chǔ)的height和width值永遠(yuǎn)非負(fù)數(shù),試圖使用setValues()方法來(lái)設(shè)置負(fù)值會(huì)觸發(fā)異常。不幸的是,由于getValues()返回d的引用,而不是d的拷貝,你可以編寫(xiě)如下的破壞性代碼:

Example ex = new Example(); 
Dimension d = ex.getValues(); 
d.height = -5; 
d.width = -10; 

  現(xiàn)在,Example對(duì)象擁有負(fù)值了!如果getValues() 的調(diào)用者永遠(yuǎn)也不設(shè)置返回的Dimension對(duì)象的width 和height值,那么僅憑測(cè)試是不可能檢測(cè)到這類(lèi)的錯(cuò)誤。

  不幸的是,隨著時(shí)間的推移,客戶代碼可能會(huì)改變返回的Dimension對(duì)象的值,這個(gè)時(shí)候,追尋錯(cuò)誤的根源是件枯燥且費(fèi)時(shí)的事情,尤其是在多線程環(huán)境中。

  更好的方式是讓getValues()返回拷貝:

public synchronized Dimension getValues(){ 
return new Dimension (d.x, d.y); 
} 

  現(xiàn)在,Example對(duì)象的內(nèi)部狀態(tài)就安全了。調(diào)用者可以根據(jù)需要改變它所得到的拷貝的狀態(tài),但是要修改Example對(duì)象的內(nèi)部狀態(tài),必須通過(guò)setValues()才可以。

  三、常見(jiàn)錯(cuò)誤3#:不必要的克隆

  我們現(xiàn)在知道了get方法應(yīng)該返回內(nèi)部數(shù)據(jù)對(duì)象的拷貝,而不是引用。但是,事情沒(méi)有絕對(duì):

/*** 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());     }   }   

  這段代碼是安全的,但是就象在錯(cuò)誤1#那樣,又作了多余的工作。Integer對(duì)象,就象String對(duì)象那樣,一旦被創(chuàng)建就是不可變的。因此,返回內(nèi)部Integer對(duì)象,而不是它的拷貝,也是安全的。

  方法getValue()應(yīng)該被寫(xiě)為:

public synchronized Integer getValue(){ 
// ’i’ is immutable, so it is safe to return it instead of a copy. 
return i; 
} 

  Java程序比C++程序包含更多的不可變對(duì)象。JDK 所提供的若干不可變類(lèi)包括:

  ·Boolean 
   ·Byte 
   ·Character 
   ·Class 
   ·Double 
   ·Float 
   ·Integer 
   ·Long 
   ·Short 
   ·String 
   ·大部分的Exception的子類(lèi)

  四、常見(jiàn)錯(cuò)誤4# :自編代碼來(lái)拷貝數(shù)組

  Java允許你克隆數(shù)組,但是開(kāi)發(fā)者通常會(huì)錯(cuò)誤地編寫(xiě)如下的代碼,問(wèn)題在于如下的循環(huán)用三行做的事情,如果采用Object的clone方法用一行就可以完成:

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];     }   }   

  這段代碼是正確的,但卻不必要地復(fù)雜。saveCopy()的一個(gè)更好的實(shí)現(xiàn)是:

void saveCopy (int[] data){ 
  try{ 
   copy = (int[])data.clone(); 
  }catch (CloneNotSupportedException e){ 
   // Can’t get here. 
  } 
} 

  如果你經(jīng)?寺(shù)組,編寫(xiě)如下的一個(gè)工具方法會(huì)是個(gè)好主意:

static int[] cloneArray (int[] data){ 
  try{ 
   return(int[])data.clone(); 
  }catch(CloneNotSupportedException e){ 
   // Can’t get here. 
  } 
} 

  這樣的話,我們的saveCopy看起來(lái)就更簡(jiǎn)潔了:

void saveCopy (int[] data){ 
  copy = cloneArray ( data); 
} 

  五、常見(jiàn)錯(cuò)誤5#:拷貝錯(cuò)誤的數(shù)據(jù)

  有時(shí)候程序員知道必須返回一個(gè)拷貝,但是卻不小心拷貝了錯(cuò)誤的數(shù)據(jù)。由于僅僅做了部分的數(shù)據(jù)拷貝工作,下面的代碼與程序員的意圖有偏差:

import java.awt.Dimension; 
/*** Example class. The height and width values should never 
 * be negative.
 */ 
public class Example{ 
  static final public int TOTAL_VALUES = 10; 
  private Dimension[] d = new Dimension[TOTAL_VALUES]; 
  public Example (){ } 

/*** Set height and width. Both height and width must be nonnegative
 * or an exception will be thrown.
 */ 
  public synchronized void setValues (int index, int height, int width) throws IllegalArgumentException{ 
   if (height < 0 || width < 0)       throw new IllegalArgumentException();       if (d[index] == null)        d[index] = new Dimension();        d[index].height = height;        d[index].width = width;     }    public synchronized Dimension[] getValues()      throws CloneNotSupportedException{       return (Dimension[])d.clone();     }   }   

  這兒的問(wèn)題在于getValues()方法僅僅克隆了數(shù)組,而沒(méi)有克隆數(shù)組中包含的Dimension對(duì)象,因此,雖然調(diào)用者無(wú)法改變內(nèi)部的數(shù)組使其元素指向不同的Dimension對(duì)象,但是調(diào)用者卻可以改變內(nèi)部的數(shù)組元素(也就是Dimension對(duì)象)的內(nèi)容。方法getValues()的更好版本為:

public synchronized Dimension[] getValues() throws CloneNotSupportedException{ 
  Dimension[] copy = (Dimension[])d.clone(); 
  for (int i = 0; i < copy.length; ++i){      // NOTE: Dimension isn’t cloneable.      if (d != null)       copy[i] = new Dimension (d[i].height, d[i].width);     }    return copy;   }   

  在克隆原子類(lèi)型數(shù)據(jù)的多維數(shù)組的時(shí)候,也會(huì)犯類(lèi)似的錯(cuò)誤。原子類(lèi)型包括int,float等。簡(jiǎn)單的克隆int型的一維數(shù)組是正確的,如下所示:

public void store (int[] data) throws CloneNotSupportedException{ 
  this.data = (int[])data.clone(); 
  // OK 
} 

  拷貝int型的二維數(shù)組更復(fù)雜些。Java沒(méi)有int型的二維數(shù)組,因此一個(gè)int型的二維數(shù)組實(shí)際上是一個(gè)這樣的一維數(shù)組:它的類(lèi)型為int[]。簡(jiǎn)單的克隆int[][]型的數(shù)組會(huì)犯與上面例子中g(shù)etValues()方法第一版本同樣的錯(cuò)誤,因此應(yīng)該避免這么做。下面的例子演示了在克隆int型二維數(shù)組時(shí)錯(cuò)誤的和正確的做法:

public void wrongStore (int[][] data) throws CloneNotSupportedException{ 
  this.data = (int[][])data.clone(); // Not OK! 
}
public void rightStore (int[][] data){ 
  // OK! 
  this.data = (int[][])data.clone(); 
  for (int i = 0; i < data.length; ++i){      if (data != null)       this.data[i] = (int[])data[i].clone();     }   }   

 

12下一頁(yè)  GO
推薦 】 【 打印
相關(guān)新聞      

本文評(píng)論       全部評(píng)論

發(fā)表評(píng)論
  • 尊重網(wǎng)上道德,遵守中華人民共和國(guó)的各項(xiàng)有關(guān)法律法規(guī)
  • 承擔(dān)一切因您的行為而直接或間接導(dǎo)致的民事或刑事法律責(zé)任
  • 本站管理人員有權(quán)保留或刪除其管轄留言中的任意內(nèi)容
  • 本站有權(quán)在網(wǎng)站內(nèi)轉(zhuǎn)載或引用您的評(píng)論
  • 參與本評(píng)論即表明您已經(jīng)閱讀并接受上述條款


點(diǎn)評(píng): 字?jǐn)?shù)
姓名:
內(nèi)容查詢