Java Assertion总结

来源:互联网 发布:安卓手机运行windows 编辑:程序博客网 时间:2024/06/11 05:47

1. 什么是Assertion

Assertion(断言)在软件开发中是一种常用的调试方式,很多开发语言中都支持这种机制.在实现中,Assertion就是在程序中的一条语句,它对一个boolean表达式进行检查,一个正确程序必须保证这个boolean表达式的值为true;如果该值为false,说明程序已经处于不正确的状 态下,系统将给出警告或退出.

2. 什么时候用Assertion

一般来说,Assertion用于保证程序最基本、关键的正确性.Assertion检查通常在开发和测试时开启.为了提高性能,在软件发布后,Assertion检查通常是关闭的.

Assertion关闭时使用Assertion不能破坏程序正常流程.

3. Assertion的打开和关闭

在启动Java程序的时候使用以下参数:

-esa 打开全部Assertion

-dsa 关闭全部Assertion

更详细的参数设置请参考java.exe的参数.

4. Assertion的语法形式

使用assert表达式的时候有两种形式:

4.1. assert exp1;

exp1为一个boolean表达式,必须为true,否则程序抛出一个AssertionError.

4.2. assert exp1:exp2;

exp1的含义同3.1;

exp2必须是一个有值的表达式(不能是返回值为void的方法调用).exp2的值将会传递给AssertionErrorconstructer, 用于提供详细的错误描述.

5. 可以使用Assertion的情况

5.1. 内部变量

如下代码:

if (i % 3 == 0) {

...

} else if (i % 3 == 1) {

...

} else { // We know (i % 3 == 2)

...

}

这段代码是对内部变量i值的判断.我们认为当执行到else语句的时候i%3==2是成立的.但是一种可能的情况是i是负数,i==-1,执行到else语句的时候并非i%3==2.这时候可以使用Assertion,代码如下:

if (i % 3 == 0) {

    ...

} else if (i % 3 == 1) {

    ...

} else {

    assert i % 3 == 2 : i;

...

}

我们可以保证当i为负数时程序可以报出错误.

if语句对应的还有switch语句.

对于以下代码:

switch(suit) {

   case Suit.CLUBS://草花

        ...

        break;

   case Suit.DIAMONDS://方块

        ...

        break;

   case Suit.HEARTS://红桃

        ...

        break;

   case Suit.SPADES://黑桃

        ...

可以使用Assertion的形式为:

default:

   assert false : suit; 

或者

default:

   throw new AssertionError(suit); 

5.2. 流程控制

在流程中认为肯定不会到达的地方使用Assertion.

如下代码:

void foo() {

    for (...) {

       if (...)

          return;

    }

    // Execution should never reach this point!!!

最好使用:

void foo() {

    for (...) {

       if (...)

          return;

    }

    assert false; // Execution should never reach this point!

5.3. 前置条件和后置条件检查

注意不能在public方法中使用!

使用前置检查:

/**

* Sets the refresh interval (which must correspond to a legal frame rate).

*

* @param  interval refresh interval in milliseconds.

*/

private void setRefreshInterval(int interval) {

    // Confirm adherence to precondition in nonpublic method

    assert interval > 0 && interval <= 1000/MAX_REFRESH_RATE : interval;

    ... // Set the refresh interval

// Recursive helper method - always called with a lock on this.

private int find(Object key, Object[] arr, int start, int len) {

   assert Thread.holdsLock(this); // lock-status assertion 

    ...

使用后置检查

void foo(final int[] array) {

    // Inner class that saves state and performs final consistency check

    class DataCopy {

        private int[] arrayCopy;

        DataCopy() { arrayCopy = (int[]) array.clone(); }

        boolean isConsistent() { return Arrays.equals(array, arrayCopy); }

    }

    DataCopy copy = null;

    // Always succeeds; has side effect of saving a copy of array

    assert ((copy = new DataCopy()) != null);

    ... // Manipulate array

    // Ensure array has same ints in same order as before manipulation.

    assert copy.isConsistent();

6. 不可以使用Assertion的情况

6.1. 不能用Assertion来检测public方法的参数

Public方法的参数检测是方法定义的一部分不管在Assertion打开还是关闭的情况下必须被遵守.使用Assertion会破坏这个定义.

6.2. 不能用Asserion来执行操作

:

// Broken! - action is contained in assertion

assert names.remove(null);

应该改成

// Fixed - action precedes assertion

boolean nullsRemoved = names.remove(null);

assert nullsRemoved;  // Runs whether or not asserts are enabled

是因为Assertion可能被关闭,本来要执行的操作也没有执行.

参考

[1]Programming With Assertions,http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html

[2]javaassert的用法理解, http://arthennala.blog.51cto.com/287631/56996

0 0
原创粉丝点击