似乎广泛接受断言语句应保留用于测试和生产中禁用,因为错误应该已经解决,并且启用断言会影响性能.然而,使用if语句进行空检查肯定也是如此.为什么这段代码被认为适合生产
if(x != null) {
x.setId(idx);
if (y != null) {
if (y.id == x.id) {
x.doSth();
}
} else {
//handle error
}
} else {
//handle error
}
Run Code Online (Sandbox Code Playgroud)
但这段代码不是吗?(假设启用了断言)
try {
assert(x != null);
x.setId(idx);
assert(y != null);
if (y.id == x.id) {
x.doSth();
}
} catch (AssertionError e) {
//handle error
}
Run Code Online (Sandbox Code Playgroud)
我理解在预期变量可能未初始化时使用if语句.然而,当它用于防御性编码时,断言似乎更优雅和可读.
我还测试了每种方法的性能:
public class AssertTest {
static final int LOOPS = 10000000;
public static void main(String[] args) {
String testStr = "";
long startNotEqualsTest = …Run Code Online (Sandbox Code Playgroud) java ×1