问题:你是如何处理这些用例的?LocalDate:缺少方法isEqualOrBefore isEqualOrAfter
- 你使用静态辅助方法吗?
- 你使用verbose equals后跟isAfter/isBefore吗?
- 你使用否定相反的条件吗?
- 你使用第三方库助手吗?
在日常业务中,我经常需要检查日期a < =日期b或日期a> =日期b。
互联网通常建议使用isBefore/isAfter方法的否定版本。
在实践中我发现,我
- 几乎从来没有得到这些否定比较正确的第一次尝试(他们应该是直观和容易)。
- 也很难读码
我想我的一部分仍然希望,我只是忽略了API中的相应方法(请!)当理解业务逻辑。
/**
* @return true if candidate >= reference </br>
* or in other words: <code>candidate.equals(reference) || candidate.isAfter(reference)</code> </br>
* or in other words: <code>!candidate.isBefore(reference) </br>
* or in other words: <code>candidate.compareTo(reference) >= 0
*/
public static boolean isEqualOrAfter(LocalDate candidate, LocalDate reference)
{
return !candidate.isBefore(reference);
}
/**
* @return true if candidate <= reference </br>
* or in other words: <code>candidate.equals(reference) || candidate.isBefore(reference)</code> </br>
* or in other words: <code>!candidate.isAfter(reference) </br>
* or in other words: <code>candidate.compareTo(reference) <= 0
*/
public static boolean isEqualOrBefore(LocalDate candidate, LocalDate reference)
{
return !candidate.isAfter(reference);
}
编辑:由于由Andreas建议,我加入了版本compareTo
方法,我希望我得到了他们的权利(未经测试)。
编辑2:例:
// Manager says: "Show me everything from 3 days ago or later" or "show me everything that's at most 3 days old"
for(Item item : items) {
// negation idiom
if(!item.getDate().isBefore(LocalDate.now().minusDays(3))) {
// show
}
// compareTo idiom
if(item.getDate().compareTo(LocalDate.now().minusDays(3)) >= 0) {
// show
}
// desired
if(item.getDate().isEqualOrAfter(LocalDate.now().minusDays(3))) {
// show
}
}
你不需要equals方法,前后都足够了。要使用equals()来测试相等性。 –
@StimpsonCat @StimpsonCat @StimpsonCat在技术上你当然是对的,但这个问题的关键在于抱怨它根本不方便(而且对我和其他人来说非常容易出错) – Zalumon
投票结束为“主要基于意见的”,因为对“你如何处理这些用例?”的回答完全是基于观点的。 ---但是,你忘记列出'compareTo()'。请注意,a.isAfter(b),a.isBefore(b)和a.isEqual(b)与a.compareTo(b)> 0完全相同,a.compareTo( b)<0'和'a.compareTo(b)== 0',所以你的'a.isEqualOrAfter(b)'和'a.isEqualOrBefore(b)'与'a.compareTo(b) )> = 0'和'a.compareTo(b)<= 0'。 – Andreas