在代码的第四行(忽略空格和注释)以及之后,我正在计算两个日期之间的月份差异。这样做是可以的,但看起来有点不专业。是否有更好的方法?
int handleAllowance(LocalDate today) {
int allowance = membership.allowance();
if (allowance == 0) return 0;
// if update was last month (or earlier)
int months = today.monthOfYear().getMaximumValue() - today.monthOfYear().getMinimumValue(); // yeah, 12, but just to be 100% correct :-)
int curMonth = (today.getYear() * months) + today. getMonthOfYear();
int updMonth = (lastAllowanceUpdate.getYear() * months) + lastAllowanceUpdate.getMonthOfYear();
if (curMonth > updMonth) {
// ...and if today is on or past update day
int updateDay = Math.min(allowanceDay, today.dayOfMonth().getMaximumValue());
if (today.getDayOfMonth() >= updateDay) {
// number of months to give allowance (in the rare case this process fails to run for 2 months or more)
int allowanceMonths = curMonth - updMonth;
// give credits
final int totalAllowance = allowance * allowanceMonths;
giveCredits(totalAllowance);
// update day
lastAllowanceUpdate = lastAllowanceUpdate.plusMonths(allowanceMonths);
// return the allowance given
return totalAllowance;
}
}
return 0;
}
allowance
是常量吗?如果不是,那么final int totalAllowance = allowance * allowanceMonths;
对于allowanceMonths > 1
可能会产生与运行整个部分allowanceMonths
次数不同的结果。 - ThomasallowanceMonths
很可能永远不会真正大于1。 - Bart van Heukelom