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

发表于:2011-2-24 10:06

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:kaduo    来源:51Testing软件测试网采编

#
java
#
JAVA
#
Java

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

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

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

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

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

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

  • String temp = "Text here";  
  • String s = new String (temp);
  •   但是这段代码包含额外的String,并非完全必要。更好的代码为:

    String s = "Text here";

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

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

  • import java.awt.Dimension;  
  • /** *//***Example class.The x and y values should never*be negative.*/ 
  • public class Example...{  
  • private Dimension d = new Dimension (00);  
  • 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类保证了它所存储的height和width值永远非负数,试图使用setValues()方法来设置负值会触发异常。不幸的是,由于getValues()返回d的引用,而不是d的拷贝,你可以编写如下的破坏性代码:

  • Example ex = new Example();  
  • Dimension d = ex.getValues();  
  • d.height = -5;  
  • d.width = -10;
  • 51/512345>
    《2023软件测试行业现状调查报告》独家发布~

    关注51Testing

    联系我们

    快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

    法律顾问:上海兰迪律师事务所 项棋律师
    版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
    投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

    沪ICP备05003035号

    沪公网安备 31010102002173号