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

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

问题描述

我知道关键字 assert 存在于 java 中.但是我不记得看到使用它的代码.可能我正在使用异常并登录我可以使用它的地方.在 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 语句、3rd-party 库等).这样,即使断言被禁用,您的方法也应该受到保护,但查看源代码的开发人员可以看到您的方法的先决条件,并在处理该类时打开断言以获得额外的安全网.

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 中使用断言是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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