Java 中的断言关键字
您是否使用 assert
关键字或抛出一些验证运行时异常?它给您带来什么好处,或者为什么您认为它不值得使用?
Do you use the assert
keyword or throw some validation runtime exception? What benefits does it give to you or why do you think it's not worth it to use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
断言将引发运行时错误 (AssertionError)如果其条件为假。断言为您提供了一种简化的方式来记录、检查和执行代码的正确性标准。好处是用于定义和操作这些正确性条件的语言级挂钩。如果您希望启用或禁用它们(关于这是否是一个好主意存在争议),您可以从 JVM 命令行执行此操作。下面的一些评论者指出,除非在调试模式下运行,否则默认情况下断言是禁用的;我的做法是始终在我的包装脚本中添加“-ea”(启用断言)。即使在性能敏感的代码中,对我来说,这种权衡也有利于我从断言中获得的安全性/正确性信心。 Oracle 断言 和 AssertionError 的 API 说明
注意预期失败和意外失败之间的区别(例外),这可能超出您的控制范围,并且断言失败 - 断言失败记录了程序员的假设,并表明程序不正确,而不是意外的外部条件或预期的异常条件。 如果发生断言失败,则解释为程序员误解或错误地表达了程序,而不是其他错误或失败的来源。
在实践中,我用它来记录我所做的明显或不明显的假设以及我在生成(特别是私有/内部)代码时想要强制执行的不变量,让我自己和其他人清楚为什么做出这些假设,它们在哪里制作,以及它们是否经过验证。同样效果比评论要好得多。这是朝着契约设计迈出的(一小步)。
有效的 Java 项目 #38“检查参数的有效性”(Google 图书,Amazon.com) 提供了关于参数检查和断言的适当使用之间区别的有用演示。
与SO相关:(在netbeans中启用断言),(断言与异常),(几乎重复,要求提供示例), (命名错误,但是非常相似的内容)
Assert will throw a runtime error (AssertionError) if its condition is false. Asserts give you a streamlined way of documenting, checking, and enforcing correctness criteria for your code. The benefits are a language-level hook for defining and manipulating these correctness conditions. To the extent that you wish to enable or disable them (there are arguments about whether or not this is a good idea) you can do so from the JVM command-line. Some commenters below note that assertions are disabled by default unless running in debug mode; my practice is to add "-ea" (enable assertions) in my wrapper scripts at all times. Even in performance sensitive code, for me the tradeoff weighs in favor of the security/correctness confidence I get from assertions. Assertions at Oracle and API Description for AssertionError
Note the distinction between expected or unexpected failures (exceptions), which may be outside your control, and assertion failures -- assertion failures document programmer assumptions, and indicate an incorrect program rather than an unexpected external condition or expected exceptional condition. If an assertion failure occurs, the interpretation is that the programmer has misunderstood or incorrectly expressed the program, rather than other sources of error or failure.
In practice, I use it to document obvious or non-obvious assumptions I make and invariants which I want to enforce as I produce (particularly private/internal) code, making it clear to myself and others why these assumptions are made, where they are made, and whether or not they are validated. Much better than comments to the same effect. This is a (small) step toward Design by Contract.
Effective Java item #38 "Check Parameters for Validity" (Google Books, Amazon.com) provides a useful presentation of the distinction between parameter checking and appropriate use of assertions.
Related on SO: (Enabling assertions in netbeans), (Assertions vs. Exceptions), (Near duplicate, asking for examples), (Badly named, but very similar content)
安德索伊是正确的。只是为了让您知道,断言的伟大之处在于您可以简单地将其关闭(如果您不在 java 命令行中传递 -ea)。当您想确保不会破坏自己的代码时,这个简单的事情使它们非常适合在开发中使用。
andersoj is correct. Just for you to know, the great thing about asserts is that you can simple turn it off (if you dont pass -ea in java command line). This simple thing make them perfect for use in development, when you want to be sure you are not breaking your own code.
正如其他人所建议的那样,使用断言进行强制检查是一种危险的做法。
当其他开发人员使用您的库时会发生什么?或者系统管理员或高级用户忘记,或者更糟糕的是不知道,在运行时使用 -ea 标志启用断言?你会失去所有这些支票,就是这样。
断言是一种开发工具。该标志的默认状态是关闭,这一事实是一个明显的泄露。
应用程序中的任何功能或优势都不应该依赖于断言的开启。
作为背景,断言的使用方式与 C/C++ 中使用该功能的方式相同。在 C/C++ 中,开发人员通常可以在编译时传入
#define DEBUG ...
来启用或禁用断言。对于 C/C++ 生产代码,通常会关闭此功能。从概念上讲,Java 也应该如此。在生产中使用条件和异常。它们本质上是同一件事。
Using asserts for mandatory checks, as others have recommended is a dangerous practice.
What happens when another developer uses your library? Or a System Admin or Power User forgets, or worse doesn't know, to enable asserts with the -ea flag at runtime? You lose all these checks, that's what.
Asserts are a development tool. The fact that the flag's default state is off is a dead give-away.
No feature or benefit in your application should ever depend on a assert being on.
As background, asserts are used the same way in C/C++ where the feature was taken from. In C/C++ a developer can usually pass in a
#define DEBUG ...
at compile time to enable or disable asserts. With C/C++ production code usually having this feature off.Conceptually, the same should be true for Java. In production use conditionals and Exceptions. They are essentially the same thing.
准确地说你的问题:
断言用于验证语句的条件。
大多数人将断言用于 String 的以下用例:(但我个人讨厌使用断言):
我更喜欢使用 google guava,它干净且能达到目的:
更多信息:http://docs.guava-libraries.googlecode.com/git/javadoc/ com/google/common/base/Strings.html
To be precise on your question :
Assert is used to validate the condition of a statement.
Most people use assert for the following use case for String : (But I personally hate to use assert for it) :
I rather like using google guava which is clean and serve the purpose :
More info : http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Strings.html
您可以使用它在开发期间启用某些功能,然后在实时站点上完全禁用它。例如,
调试语句将在实时站点上添加零开销。
you can use it to enable something during dev, then disable it completely on live site. for example
the debug statement will add zero overhead on live site.