简体   繁体   English

Java中的assert关键字应该在哪里使用?

[英]Where should I use the assert keyword in Java?

I know that the assert keyword should be used when we want to make a bug come out, but is it ok to use it in situations like the one that follows?我知道当我们想要让 bug 出来时应该使用 assert 关键字,但是在像下面这样的情况下可以使用它吗? The redirectAdd method only receives args whose length is more than 3, I added it for anyone who will read the method in the future to give some logical context, is it ok or it's better if I remove it and add a comment instead? redirectAdd 方法只接收长度大于 3 的 args,我为将来阅读该方法的任何人添加它以提供一些逻辑上下文,是否可以,或者如果我删除它并添加注释会更好?

The code I'm referring to:我指的代码:

private static boolean redirectAdd(Player player, String[] args, ItemStack mainHandItem) {
    assert args.length > 3;
    if (args.length == 4) {
        //more actions & another return
    } else if (args.length == 5) {
        //more actions & another return
    } else if (args.length == 6) {
        //more actions & another return
    } else {
        player.sendMessage(ChatColor.RED + "There are too many arguments! The last should be " + args[5] + "");
        return false;
    }
}

Short answer:简短回答:

Assert should not be used for other purposes than debugging, especially not in production code.断言不应该用于调试以外的其他目的,尤其是在生产代码中。 The reason for this is that these assert checks can be disabled.这样做的原因是可以禁用这些断言检查。 They are disabled by default and need to be enabled by using the -ae compiler flag (thanks @user16320675 for pointing this out).默认情况下它们是禁用的,需要使用-ae编译器标志启用(感谢 @user16320675 指出这一点)。

For long answer and further information, see here: What does the Java assert keyword do, and when should it be used?有关详细答案和更多信息,请参见此处: Java assert 关键字的作用是什么,何时使用?

The assert keyword is used when debugging code.调试代码时使用 assert 关键字。 The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. assert 关键字可让您测试代码中的条件是否返回 True,否则程序将引发 AssertionError。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM