在任何情况下都可以将此条件评估为 "true" 吗?
Could be this condition evaluated to "true" in any case?
我必须重构一些遗留代码,我已经开始做一些测试。这是正在测试的方法:
public static synchronized String getWeekFromDate(Date date) {
String strYyear = new SimpleDateFormat("yyyy").format(date);
String strMonth = new SimpleDateFormat("MM").format(date);
String strWeek = new SimpleDateFormat("ww").format(date);
int month = Integer.parseInt(strMonth);
if (month > 1 && "01".equals(strWeek)) {
int year = Integer.parseInt(strYyear);
return (year + 1) + "01";
}
return new SimpleDateFormat("yyyyww").format(date);
}
我写了五个测试用例,都是绿色的。现在,我想重构它。条件 if (month > 1 && "01".equals(strWeek))
对我来说毫无意义。可以读作:
Given a date, it's true when the month is not January and the week is
the first one in that year
我说的对吗?是否有意义?我很确定我可以删除那段代码而不会产生任何后果。
我的测试用例是(全绿):
- 鉴于 2018-01-03,它应该 return "201801"
- 鉴于 2018-02-01,它应该 return "201805"
- 鉴于 2018-08-15,它应该 return "201833"
不,您不能安全地删除该代码。年末第一周的日期符合该条件。
考虑以下情况,对于 2017 年 12 月 31 日,您最终得到的结果字符串为 201701
:
Date date = new SimpleDateFormat("yyyy/MM/dd").parse("2017/12/31");
String weekYear = new SimpleDateFormat("yyyyww").format(date);
System.out.println(weekYear); // "201701" - WRONG
然而,有一个比您当前拥有的代码更优雅的解决方案,它依赖于 SimpleDateFormat
的 week year(Y
而不是y
) 模式:
Date date = new SimpleDateFormat("yyyy/MM/dd").parse("2017/12/31");
String weekYear = new SimpleDateFormat("YYYYww").format(date);
System.out.println(weekYear); // "201801" - CORRECT
在单元测试中,您应该首先解决边界情况。像一年中的第一天和最后一天这样的日期在这里绝对符合边界条件。
我必须重构一些遗留代码,我已经开始做一些测试。这是正在测试的方法:
public static synchronized String getWeekFromDate(Date date) {
String strYyear = new SimpleDateFormat("yyyy").format(date);
String strMonth = new SimpleDateFormat("MM").format(date);
String strWeek = new SimpleDateFormat("ww").format(date);
int month = Integer.parseInt(strMonth);
if (month > 1 && "01".equals(strWeek)) {
int year = Integer.parseInt(strYyear);
return (year + 1) + "01";
}
return new SimpleDateFormat("yyyyww").format(date);
}
我写了五个测试用例,都是绿色的。现在,我想重构它。条件 if (month > 1 && "01".equals(strWeek))
对我来说毫无意义。可以读作:
Given a date, it's true when the month is not January and the week is the first one in that year
我说的对吗?是否有意义?我很确定我可以删除那段代码而不会产生任何后果。
我的测试用例是(全绿):
- 鉴于 2018-01-03,它应该 return "201801"
- 鉴于 2018-02-01,它应该 return "201805"
- 鉴于 2018-08-15,它应该 return "201833"
不,您不能安全地删除该代码。年末第一周的日期符合该条件。
考虑以下情况,对于 2017 年 12 月 31 日,您最终得到的结果字符串为 201701
:
Date date = new SimpleDateFormat("yyyy/MM/dd").parse("2017/12/31");
String weekYear = new SimpleDateFormat("yyyyww").format(date);
System.out.println(weekYear); // "201701" - WRONG
然而,有一个比您当前拥有的代码更优雅的解决方案,它依赖于 SimpleDateFormat
的 week year(Y
而不是y
) 模式:
Date date = new SimpleDateFormat("yyyy/MM/dd").parse("2017/12/31");
String weekYear = new SimpleDateFormat("YYYYww").format(date);
System.out.println(weekYear); // "201801" - CORRECT
在单元测试中,您应该首先解决边界情况。像一年中的第一天和最后一天这样的日期在这里绝对符合边界条件。