Java开发程序员必知的Java编程的10种错误

开发 后端
做为程序员,在编写代码的长期经历中,我们一定会发现一些常见的错误,就算是注意再注意还是会出现。这不是技术问题。

       作为程序员在程序开发的过程中难免的要出现一些不是自己水平问题二出现的一些常见的错误。本文就为大家介绍一些常见在Java开发过程中遇见的一些常见的错误。

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

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

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

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

  但是,这段代码性能差,而且没有必要这么复杂。你还可以用以下的方式来重写上面的代码:

  1. String temp = "Text here";  
  2. String s = new String (temp); 

  但是这段代码包含额外的String,并非完全必要。更好的代码为:

  1. String s = "Text here"

二、常见错误2:没有克隆(clone)返回的对象

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

  1.   import java.awt.Dimension;  
  2.   /** *//***Example class.The x and y values should never*be negative.*/ 
  3.   public class Example...{  
  4.   private Dimension d = new Dimension (00);  
  5.   public Example ()...{ }  
  6.   /** *//*** Set height and width. Both height and width must be nonnegative * or an exception is thrown.*/ 
  7.   public synchronized void setValues (int height,int width) throws IllegalArgumentException...{  
  8.   if (height <0 || width <0)  
  9.   throw new IllegalArgumentException();  
  10.   d.height = height;  
  11.   d.width = width;  
  12.   }  
  13.   public synchronized Dimension getValues()...{  
  14.   // Ooops! Breaks encapsulation  
  15.   return d;  
  16.   }  
  17.   } 

  Example类保证了它所存储的height和width值永远非负数,试图使用setValues()方法来设置负值会触发异常。不幸的是,由于getValues()返回d的引用,而不是d的拷贝,你可以编写如下的破坏性代码:

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

  现在,Example对象拥有负值了!如果getValues() 的调用者永远也不设置返回的Dimension对象的width 和height值,那么仅凭测试是不可能检测到这类的错误。

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

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

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

  现在,Example对象的内部状态就安全了。调用者可以根据需要改变它所得到的拷贝的状态,但是要修改Example对象的内部状态,必须通过setValues()才可以。

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

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

  1.  /** *//*** Example class.The value should never * be negative.*/ 
  2.   public class Example...{  
  3.   private Integer i = new Integer (0);  
  4.   public Example ()...{ }  
  5.   /** *//*** Set x. x must be nonnegative* or an exception will be thrown*/ 
  6.   public synchronized void setValues (int x) throws IllegalArgumentException...{  
  7.   if (x <0)  
  8.   throw new IllegalArgumentException();  
  9.   i = new Integer (x);  
  10.   }  
  11.   public synchronized Integer getValue()...{  
  12.   // We can’t clone Integers so we makea copy this way.  
  13.   return new Integer (i.intValue());  
  14.   }  
  15.   } 

  这段代码是安全的,但是就象在错误1#那样,又作了多余的工作。Integer对象,就象String对象那样,一旦被创建就是不可变的。因此,返回内部Integer对象,而不是它的拷贝,也是安全的。

  方法getValue()应该被写为:

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

  Java程序比C++程序包含更多的不可变对象。JDK 所提供的若干不可变类包括:

  1.   ·Boolean  
  2.   ·Byte  
  3.   ·Character  
  4.   ·Class  
  5.   ·Double  
  6.   ·Float  
  7.   ·Integer  
  8.   ·Long  
  9.   ·Short  
  10.   ·String  
  11.   ·大部分的Exception的子类 

 

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

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

  1.   public class Example...{  
  2.   private int[] copy;  
  3.   /** *//*** Save a copy of ’data’. ’data’ cannot be null.*/ 
  4.   public void saveCopy (int[] data)...{  
  5.   copy = new int[data.length];  
  6.   for (int i = 0; i  
  7.   copy[i] = data[i];  
  8.   }  
  9.   } 

  这段代码是正确的,但却不必要地复杂。saveCopy()的一个更好的实现是:

  1.  void saveCopy (int[] data)...{  
  2.   try...{  
  3.   copy = (int[])data.clone();  
  4.   }catch (CloneNotSupportedException e)...{  
  5.   // Can’t get here.  
  6.   }  
  7.   } 

  如果你经常克隆数组,编写如下的一个工具方法会是个好主意:

  1. static int[] cloneArray (int[] data)...{  
  2.   try...{  
  3.   return(int[])data.clone();  
  4.   }catch(CloneNotSupportedException e)...{  
  5.   // Can’t get here.  
  6.   }  
  7.   } 

 

  这样的话,我们的saveCopy看起来就更简洁了:

  1. void saveCopy (int[] data)...{  
  2.  copy = cloneArray ( data);  
  3.  } 

#p#

五、常见错误5:拷贝错误的数据

  有时候程序员知道必须返回一个拷贝,但是却不小心拷贝了错误的数据。由于仅仅做了部分的数据拷贝工作,下面的代码与程序员的意图有偏差:

  1.   import java.awt.Dimension;  
  2.   /** *//*** Example class. The height and width values should never * be  
  3.   negative. */ 
  4.   public class Example...{  
  5.   static final public int TOTAL_VALUES = 10;  
  6.   private Dimension[] d = new Dimension[TOTAL_VALUES];  
  7.   public Example ()...{ }  
  8.   /** *//*** Set height and width. Both height and width must be nonnegative * or an exception will be thrown. */ 
  9.   public synchronized void setValues (int index, int height, int width) throws IllegalArgumentException...{  
  10.   if (height <0 || width <0)  
  11.   throw new IllegalArgumentException();  
  12.   if (d[index] == null)  
  13.   d[index] = new Dimension();  
  14.   d[index].height = height;  
  15.   d[index].width = width;  
  16.   }  
  17.   public synchronized Dimension[] getValues()  
  18.   throws CloneNotSupportedException...{  
  19.   return (Dimension[])d.clone();  
  20.   }  
  21.   } 

  这儿的问题在于getValues()方法仅仅克隆了数组,而没有克隆数组中包含的Dimension对象,因此,虽然调用者无法改变内部的数组使其元素指向不同的Dimension对象,但是调用者却可以改变内部的数组元素(也就是Dimension对象)的内容。方法getValues()的更好版本为:

  1.   public synchronized Dimension[] getValues() throws CloneNotSupportedException...{  
  2.   Dimension[] copy = (Dimension[])d.clone();  
  3.   for (int i = 0; i  
  4.   // NOTE: Dimension isn’t cloneable.  
  5.   if (d != null)  
  6.   copy[i] = new Dimension (d[i].height, d[i].width);  
  7.   }  
  8.   return copy;  
  9.   } 

  在克隆原子类型数据的多维数组的时候,也会犯类似的错误。原子类型包括int,float等。简单的克隆int型的一维数组是正确的,如下所示:

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

  拷贝int型的二维数组更复杂些。Java没有int型的二维数组,因此一个int型的二维数组实际上是一个这样的一维数组:它的类型为int[]。简单的克隆int[][]型的数组会犯与上面例子中getValues()方法第一版本同样的错误,因此应该避免这么做。下面的例子演示了在克隆int型二维数组时错误的和正确的做法:

  1.    public void wrongStore (int[][] data) throws CloneNotSupportedException...{  
  2.   this.data = (int[][])data.clone(); // Not OK!  
  3.   }  
  4.   public void rightStore (int[][] data)...{  
  5.   // OK!  
  6.   this.data = (int[][])data.clone();  
  7.   for (int i = 0; i  
  8.   if (data != null)  
  9.   this.data[i] = (int[])data[i].clone();  
  10.   }  
  11.   } 

六、常见错误6:检查new 操作的结果是否为null

  Java编程新手有时候会检查new操作的结果是否为null。可能的检查代码为:

  1. Integer i = new Integer (400);  
  2. if (i == null)  
  3. throw new NullPointerException(); 

 

  检查当然没什么错误,但却不必要,if和throw这两行代码完全是浪费,他们的唯一功用是让整个程序更臃肿,运行更慢。

  C/C++程序员在开始写java程序的时候常常会这么做,这是由于检查C中malloc()的返回结果是必要的,不这样做就可能产生错误。检查C++中new操作的结果可能是一个好的编程行为,这依赖于异常是否被使能(许多编译器允许异常被禁止,在这种情况下new操作失败就会返回null)。在java 中,new 操作不允许返回null,如果真的返回null,很可能是虚拟机崩溃了,这时候即便检查返回结果也无济于事。

七、常见错误7:用== 替代.equals

  在Java中,有两种方式检查两个数据是否相等:通过使用==操作符,或者使用所有对象都实现的.equals方法。原子类型(int, flosat, char 等)不是对象,因此他们只能使用==操作符,如下所示:

  1.  int x = 4;  
  2.  int y = 5;  
  3.  if (x == y)  
  4.  System.out.println ("Hi");  
  5.  // This ’if’ test won’t compile.  
  6.  if (x.equals (y))  
  7.  System.out.println ("Hi"); 

  对象更复杂些,==操作符检查两个引用是否指向同一个对象,而equals方法则实现更专门的相等性检查。

  更显得混乱的是由java.lang.Object 所提供的缺省的equals方法的实现使用==来简单的判断被比较的两个对象是否为同一个。

  许多类覆盖了缺省的equals方法以便更有用些,比如String类,它的equals方法检查两个String对象是否包含同样的字符串,而Integer的equals方法检查所包含的int值是否相等。

  大部分时候,在检查两个对象是否相等的时候你应该使用equals方法,而对于原子类型的数据,你用该使用==操作符
#p#
八、常见错误8:混淆原子操作和非原子操作

  Java保证读和写32位数或者更小的值是原子操作,也就是说可以在一步完成,因而不可能被打断,因此这样的读和写不需要同步。以下的代码是线程安全(thread safe)的:

  1.   public class Example...{  
  2.   private int value; // More code here...  
  3.   public void set (int x)...{  
  4.   // NOTE: No synchronized keyword  
  5.   this.value = x;  
  6.   }  
  7.   } 

  不过,这个保证仅限于读和写,下面的代码不是线程安全的:

  1.   public void increment ()...{  
  2.   // This is effectively two or three instructions:  
  3.   // 1) Read current setting of ’value’.  
  4.   // 2) Increment that setting.  
  5.   // 3) Write the new setting back.  
  6.   ++this.value;  
  7.   } 

  在测试的时候,你可能不会捕获到这个错误。首先,测试与线程有关的错误是很难的,而且很耗时间。其次,在有些机器上,这些代码可能会被翻译成一条指令,因此工作正常,只有当在其它的虚拟机上测试的时候这个错误才可能显现。因此最好在开始的时候就正确地同步代码:

  1.  public synchronized void increment ()...{  
  2.  ++this.value;  
  3.  } 

九、常见错误9:在catch 块中作清除工作

  一段在catch块中作清除工作的代码如下所示:

  1.   OutputStream os = null;  
  2.   try...{  
  3.   os = new OutputStream ();  
  4.   // Do something with os here.  
  5.   os.close();  
  6.   }catch (Exception e)...{  
  7.   if (os != null)  
  8.   os.close();  
  9.   } 

  尽管这段代码在几个方面都是有问题的,但是在测试中很容易漏掉这个错误。下面列出了这段代码所存在的三个问题:

  1.语句os.close()在两处出现,多此一举,而且会带来维护方面的麻烦。

  2.上面的代码仅仅处理了Exception,而没有涉及到Error。但是当try块运行出现了Error,流也应该被关闭。

  3.close()可能会抛出异常。

  上面代码的一个更优版本为:

  1. OutputStream os = null;  
  2. try...{  
  3. os = new OutputStream ();  
  4. // Do something with os here.  
  5. }finally...{  
  6. if (os != null)  
  7. os.close();  

  这个版本消除了上面所提到的两个问题:代码不再重复,Error也可以被正确处理了。但是没有好的方法来处理第三个问题,也许最好的方法是把close()语句单独放在一个try/catch块中。

十、常见错误10: 增加不必要的catch 块

  一些开发者听到try/catch块这个名字后,就会想当然的以为所有的try块必须要有与之匹配的catch块。

  C++程序员尤其是会这样想,因为在C++中不存在finally块的概念,而且try块存在的唯一理由只不过是为了与catch块相配对。

  增加不必要的catch块的代码就象下面的样子,捕获到的异常又立即被抛出:

  1.  try...{  
  2.         // Nifty code here  
  3.        }catch(Exception e)...  
  4.        {  
  5.         throw e;  
  6.         }finally...{  
  7.          // Cleanup code here  
  8.         } 
   

不必要的catch块被删除后,上面的代码就缩短为:

  1. try...{  
  2.   // Nifty code here  
  3.   }finally...{  
  4.   // Cleanup code here  
  5.   } 


在本文中我为大家分享了十个常见的在Java开发中常见的易发的错误,希望大家有了这方面的哈东东以后多多分享。

【编辑推荐】

  1. Java类中域和方法设置中的常见错误
  2. 浅谈如何避免Java项目评估中的常见错误
  3. JAVA几个常见错误简析(下)
  4. JAVA几个常见错误简析(上)
责任编辑:佚名 来源: it168
相关推荐

2012-06-28 14:01:30

Java程序员排序

2021-01-07 09:57:46

软件架构服务器

2015-05-19 14:34:17

程序员编程语言

2015-12-04 09:33:15

程序员前端演进史

2014-02-09 10:30:17

Python程序员工具

2021-06-04 10:15:17

JavaSQL编程语言

2019-01-30 14:14:16

LinuxUNIX操作系统

2019-07-23 17:20:02

Java微服务软件架构模式

2017-08-03 14:25:13

Python陷阱与缺陷

2023-10-26 18:05:37

Git命令差异

2015-10-28 09:33:31

程序员崩溃编程语言

2018-07-11 14:04:53

Python陷阱缺陷

2020-10-26 15:20:05

架构运维技术

2023-09-12 11:25:15

2015-11-30 11:01:34

前端程序员历史

2018-09-29 16:10:02

编程语言Java程序员

2020-05-13 11:20:57

MySQL规范数据库

2024-01-10 18:01:22

编程技巧Java 12

2011-07-11 10:12:59

2011-05-31 15:19:17

点赞
收藏

51CTO技术栈公众号