Java代码常见的十种错误

2012-11-12

    每一个程序员在编写代码的过程中都免不了出现错误或是小的失误,这些小的错误和失误往往使得程序员还得返工。那么,如何才能尽量避免这些错误的发生呢?笔者总结只有在日常的编写代码中总结出经验,在这篇文章中,笔者列出了10个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 (0, 0);
    public Example ()…{ }
    /** *//*** Set border="1" Height and width. Both border="1" Height and width must be nonnegative * or an exception is thrown.*/
    public synchronized void setValues (int border="1" Height,int width) throws IllegalArgumentException…{
    if (border="1" Height <0 || width <0)
    throw new IllegalArgumentException();
    d.border="1" height = border="1" Height;
    d. width = width;
    }
    public synchronized Dimension getValues()…{
    // Ooops! Breaks encapsulation
    return d;
    }  }
    Example类保证了它所存储的border="1" Height和width值永远非负数,试图使用setValues()方法来设置负值会触发异常。不幸的是,由于getValues()返回d的引用,而不是d的拷贝,你可以编写如下的破坏性代码:
    Example ex = new Example();
    Dimension d = ex.getValues();
    d.border="1" height = -5;  d. width = -10;
    现在,Example对象拥有负值了!如果getValues() 的调用者永远也不设置返回的Dimension对象的width 和border="1" Height值,那么仅凭测试是不可能检测到这类的错误。
    不幸的是,随着时间的推移,客户代码可能会改变返回的Dimension对象的值,这个时候,追寻错误的根源是件枯燥且费时的事情,尤其是在多线程环境中。
    更好的方式是让getValues()返回拷贝:
    public synchronized Dimension getValues()…{
    return new Dimension (d.x, d.y);  }
    现在,Example对象的内部状态就安全了。调用者可以根据需要改变它所得到的拷贝的状态,但是要修改Example对象的内部状态,必须通过setValues()才可以。  三、常见错误3:不必要的克隆
    我们现在知道了get方法应该返回内部数据对象的拷贝,而不是引用。但是,事情没有绝对:  /** *//*** 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());
    }  }

    考试大温馨提示:本内容来源于网络,仅代表作者个人观点,与本站立场无关,仅供您学习交流使用。其中可能有部分文章经过多次转载而造成文章内容缺失、错误或文章作者不详等问题,请您谅解。如有侵犯您的权利,请联系我们,本站会立即予以处理。

    编辑推荐:

    JavaTimer和TimerTask详解

    8个改善Java遗留系统的技巧

    Java数组之初始化及实例代码

分享到:
0
相关阅读
友情链接
© 2018 我考网 http://www.woexam.com 中国互联网举报中心 湘ICP备18023104号 京公网安备 11010802020116号
违法和不良信息举报:9447029@qq.com