gpt4 book ai didi

java - 需要帮助理解作者反对一段代码的论点

转载 作者:行者123 更新时间:2023-12-01 21:54:31 25 4
gpt4 key购买 nike

我正在向Java:Just in Time,John Latham学习Java。我有点困惑。

我们有一个程序,它从命令行参数获取当前年龄并计算明年的年龄。

public class AgeNextYear
{
public static void main(String[] args)
{
int ageNow = Integer.parseInt(args[0]);
int ageNextYear = ageNow + 1;

System.out.println("Your age now is " + ageNow);
System.out.println("Your age next year will be " + ageNextYear);
} // main
} // class AgeNextYear

用户可以通过两种方法使该程序失败。首先,他们可能会在没有命令行参数,因此在尝试访问 args[0] 时会出现问题。其次,它们可能提供的参数不是整数的字符串表示形式,因此 Integer.parseInt() 方法将无法将值解释为 int。然后,为了避免这段代码中可能出现的两种异常,我们可以在 AgeNextYear 程序中添加一些代码来检查用户输入的有效性。那么代码是

 public class AgeNextYear
{
// Return true if and only if given string is all digits and non empty.
private static boolean isNonEmptyDigits(String shouldBeDigits)
{
boolean okaySoFar = shouldBeDigits.length() != 0;
int index = 0;
while(okaySoFar && index < shouldBeDigits.length())
{
okaySoFar = Character.isDigit(shouldBeDigits.charAt(index));
index ++;
} // while
return okaySoFar;
} // isNonEmptyDigits


// Check argument and compute result or report error.
public static void main(String[] args)
{
if(args.length > 0 && isNonEmptyDigits(args[0]))
{
int ageNow = Integer.parseInt(args[0]);
int ageNextYear = ageNow + 1;

System.out.println("Your age now is " + ageNow);
System.out.println("Your age next year will be " + ageNextYear);
} // if
else
System.out.println("Please supply your age, as whole number.");
} // main

} // class AgeNextYear

然后,这本书的作者说,

Whilst it is true that we have made the program robust against exceptions, we should not be satisfied with this approach. First, it was rather a lot of work – the program has doubled in size. [-- Second, the checks that our new parts of the code make are also being made by the parts of the program that caused the exceptions in the first place. That is, the implementation of args[0] in an expression contains a check that the length of args is at least one, otherwise it will create an Exception. Also, the code inside Integer.parseInt() is surely checking that each character of the argument is a digit. --]

我不明白他括号里的意思[-- --]。

最佳答案

糟糕代码的标志之一是代码数量很多。 “工作量很大”的原因是因为这本书的作者是一个糟糕的程序员。

以下是一个优秀程序员如何编写代码来完成完全相同的事情,但代码更少:

public static void main(String[] args) {
if (args.length == 0 || !args[0].matches("\\d{1,3}")) // age must be in range 0-999
System.out.println("Please supply your age, as whole number.");
else
System.out.println("Your age now is " + args[0] + "\nYour age next year will be " + (Integer.parseInt(args[0]) + 1));
}

这就是整个程序。

请注意,您根本不需要 ageNowageNextYear 变量,而使用 String.matches() 方法检查字符串是否仅由数字组成。

应该注意的是,“检查字符串是否仅为数字”不能在调用 Integer.parseInt() 时防止异常 - 如果您向其传递一个数字大于 2147483647 (即 Integer.MAX_VALUE )它会爆炸。

如果您想要适当的保护,请捕获预期的异常:

public static void main(String[] args) {
try {
System.out.println("Your age now is " + args[0] + "\nYour age next year will be " + (Integer.parseInt(args[0]) + 1));
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
System.out.println("Please supply your age, as whole number.");
}
}

这是完全健壮的,而且代码更少。

关于java - 需要帮助理解作者反对一段代码的论点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34596563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com