是否需要额外检查将字符串解析为 LocalDate 对象?

Kai*_* Hu 0 java defensive-programming exception isodate localdate

我正在为一些验证用户出生日期的遗留代码编写一些测试。我在课堂上遇到了以下方法。我怀疑try块中的if语句是否必要。根据我的理解,如果 parse 函数成功返回一个 LocalDate 对象,那么 date.toString() 应该总是等于输入的 dobstr,并且不需要做额外的检查。我错过了什么吗?我想不出任何我们需要额外检查的情况。请帮忙。谢谢!

private LocalDate format(String dobStr) throws Exception {
        LocalDate date = null;
        try {
            date = LocalDate.parse(dobStr, DateTimeFormatter.ISO_DATE);
            if (!dobStr.equals(date.toString())) {
                 throw new DateTimeParseException("some message");
            }
        }
        catch (DateTimeParseException ex) {
            throw ex;
        }
        return date;
}
Run Code Online (Sandbox Code Playgroud)

这是我在 DateTimeFormatter.ISO_DATE 的源代码中找到的

public static final DateTimeFormatter ISO_DATE;
static {
    ISO_DATE = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .append(ISO_LOCAL_DATE)
            .optionalStart()
            .appendOffsetId()
            .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
}
Run Code Online (Sandbox Code Playgroud)

NoD*_*und 5

我可以看到进行toString()检查的唯一原因是避免宽大问题:解析器可能宽大并尝试解释错误的值(例如:2020-12-32 可以解释为 2021-01-01)。

如果你想删除它,你应该检查是否DateTimeFormatter.ISO_DATEResolverStyle.STRICT默认的。假设默认情况下它不是 STRICT,您的代码可能是:

private LocalDate format(String dobStr) throws Exception {
  return LocalDate.parse(dobStr, DateTimeFormatter.ISO_DATE.withResolverStyle(ResolverStyle.STRICT));
}
Run Code Online (Sandbox Code Playgroud)