在Java中使用assert是一种好习惯吗? [英] Is it good practice to use assert in Java?

查看:510
本文介绍了在Java中使用assert是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道java中存在关键字 assert 。但是我不记得看到使用它的代码。可能我正在使用异常和登录我可以使用它的地方。在java中使用 assert 关键字是一个好习惯吗?

I know that the keyword assert exists in java. However I don't remember seeing code that uses it. Probably I am using exceptions and logging in places where I could have used it. Is it a good practice to use the assert keyword in java?

编辑:我知道断言通常是一种好习惯。我的问题是,更准确一点,如果在java中,断言的BKM使用 assert 关键字而不是使用异常,日志记录和其他技术。

EDIT: I know that assertions in general is a good practice. my question is, to be more accurate, if in java the BKM of assertion is using the assert keyword rather than using exception, logging and other techniques.

推荐答案

未使用断言的主要原因是默认情况下未启用断言。因此,如果您的条件非常重要,需要断言,则不能依赖启用断言来完成工作。

The main reason assertions are not used is because they are not enabled by default. Therefore if you have a condition that is important enough to require an assertion you can't rely on assertions being enabled to get the job done.

正如其他答案已正确陈述它们专为开发时测试和调试而设计,因为如果在生产中禁用断言,它们就不会花费任何成本。我认为最好在测试框架中创建显式测试(例如边缘条件的单元测试),而不是依赖于在测试时启用断言的人。

As other answers have correctly stated they're designed for development-time testing and debugging because they cost nothing if assertions are disabled in production. I think it's better to create explicit tests in your testing framework (e.g. a unit test for edge conditions) than rely on someone enabling assertions while testing.

然而这是一个很好的例子我已经看到使用断言是检查私有方法参数。由于您控制对这些方法的访问,因此您可以检查您自己的类是否正确使用该方法,而您的公共方法使用更可靠的参数检查技术(注释,if语句,第三方库等)。这样,即使断言被禁用,您的方法也应该受到保护,但是查看源代码的开发人员可以查看您的方法的前提条件,并在处理该类时为额外的安全网打开断言。

However a good example I've seen for using assertions is checking private method arguments. Since you control the access to those methods you can check that your own class is using the method correctly while your public methods use more reliable argument checking techniques (annotations, if statements, 3rd-party libraries, etc). That way even if assertions are disabled your method should be protected but developers looking at the source code can see the preconditions for your method and turn assertions on for an extra safety net when working on that class.

这篇关于在Java中使用assert是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆