如何解决我如何重构以解决冗余空检查
在下面的代码块中获取冗余的空检查错误。有人可以帮我重构它吗?
private Date pickRecent(Date d1,Date d2,Date d3,Date crd) {
logger.debug("d1: " + d1 + " d2: " + d2 + " d3: " + d3 + " crd: " + crd);
// all null
if (d1 == null && d2 == null && d3 == null) return crd;
logger.debug("through all");
// two null
if (d1 == null && d2 == null) return d3;
if (d1 == null && d3 == null) return d2;
if (d2 == null && d3 == null) return d1;
logger.debug("through two");
// one null
if (d1 == null) if (d2.after(d3)) return d2; else return d3;
if (d2 == null) if (d1.after(d3)) return d1; else return d3;
if (d3 == null) if (d1.after(d2)) return d1; else return d2;
logger.debug("through one");
// none null
if (d1.after(d2) && d1.after(d3)) return d1;
if (d2.after(d1) && d2.after(d3)) return d2;
if (d3.after(d1) && d3.after(d2)) return d3;
if (d1.equals(d2) && d1.equals(d3)) return d1;
logger.debug("through none");
return null;
}
解决方法
这是一种可能的解决方案...
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
public class RecentDate
{
public static void main(String[] args)
{
System.out.println(pickRecent(new Date(1,1,1),new Date(2,2,2),new Date(3,3,3),new Date(4,4,4)));
System.out.println(pickRecent(null,null,null));
}
private static Date pickRecent(Date...dates)
{
return Arrays.stream(dates).filter(d -> d != null).max(Comparator.naturalOrder()).orElse(null);
}
}
输出:
Wed May 04 00:00:00 CST 1904
null
,
public static Date pickRecent(Date one,Date two,Date three,Date crd) {
Set<Date> unique = new TreeSet<>(Comparator.reverseOrder());
if (one != null)
unique.add(one);
if (two != null)
unique.add(two);
if (three != null)
unique.add(three);
return unique.size() == 1 ? unique.iterator().next() : crd;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。