小编afx*_*xgx的帖子

哪个更好 - Integer.parseInt()并在转换之前捕获异常或验证带有模式的String?

我已经看到两种样式用于检查变量是否是Java中的有效整数.一个通过执行Integer.parseInt并捕获任何结果异常.另一个是使用Pattern.以下哪项是更好的方法?

String countStr;
int count;
try {
    count = Integer.parseInt(countStr);
} catch (Exception e) {
    //return as the variable is not a proper integer.
    return;
}
Run Code Online (Sandbox Code Playgroud)

要么

String integerRegex = "([0-9]{0,9})";
if (countStr.isEmpty() || !Pattern.matches(integerRegex, countStr)) {
    //return as the variable is not a proper integer.
    return;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,是否正在进行Integer.parseInt()并捕获异常以验证验证标准方法int?我承认我的正则表达并不完美.但是,Java中是否有可用于验证int的内置方法?实际上做一些验证而不是简单地捕获异常是不是更好?

java

8
推荐指数
1
解决办法
8262
查看次数

Java编码标准:变量声明

根据 Java 编码标准,以下哪项是最佳实践

public void function1(){
 boolean valid = false;
 //many lines of code
 valid = validateInputs();
 //many lines of code
}
Run Code Online (Sandbox Code Playgroud)

或者

public void function1(){
 //many lines of code
 boolean valid = validateInputs();
 //many lines of code
}
Run Code Online (Sandbox Code Playgroud)

这里的“有效”不是指退货。它的作用域仅在函数内部。有时仅在一个 if 条件下

我通常编写类似于第二种情况的代码。看来我的上级不喜欢这样,并在我提交审查时修改了代码。我的方法不正确有什么具体原因吗?

我认为第一种方法的缺点是以后很难将该方法重构为多个方法。

java coding-style

1
推荐指数
1
解决办法
1283
查看次数

标签 统计

java ×2

coding-style ×1