2008-04-10

我们需要assert吗[二]

关键字: assert
    /**
     * Internal constructor for already-normalized pathname strings.
     * The parameter order is used to disambiguate this method from the
     * public(File, String) constructor.
     */
    private File(String child, File parent) {
        assert parent.path != null;
        assert (!parent.path.equals(""));
        this.path = fs.resolve(parent.path, child);
	    this.prefixLength = parent.prefixLength;
    }


上面的这段代码是无意间看到的,看到后,觉得很是奇怪,在一个这么公用的java.io.File居然用了assert。

我继续翻java的源代码,试着去找,发现使用了assert的地方甚少。

当然,在这里就算编译运行不开启assert功能,也影响不大,不会因为使用了assert而使代码的语义逻辑发生改变。

  • org.eclipse.jface.util.Assert AssertionFailedException
  • org.eclipse.core.runtime.Assert IllegalArgumentException
  • junit.framework.Assert AssertionFailedError

都提供了替代assert功能的Assert类,上面的几个Assert类的功能和代码都几乎相似,在断言失败后,也都会抛出一个对应的断言失败异常。

看了上面替代assert的Assert类,其实都是在做一件事情,就是规避程序自身的问题,就是规避程序员引入的错误.

  • 如果不使用assert,就可以使用Assert类,而不用去依赖一个assertion开启与关闭的开关.
  • 如果使用assert,则记得在调试代码时候要开启,发布后,肯定是需要关闭assert功能的.
评论
发表评论

您还没有登录,请登录后发表评论

lggege
搜索本博客
我的相册
49edb3d3-94ce-3f1d-b3b2-d2dd99204513-thumb
IndexCardGenerator
共 13 张
最近加入圈子
存档
最新评论