考虑以下课程
Class RequestBodyResource {
private RequestVariable1 att1;
private String att2;
private String att3;
}
我有一个方法应该在2个条件下返回false
基本上“至少一个”或“至多一个”
相同的代码是
public boolean validateExactlyOneRequiredRequestParam(RequestBodyResource request) {
//The below 3 conditions are to test that only one request is present
if(StringUtils.isNotEmpty(request.getAtt3()) && null != request.getAtt1()) {
return false;
}
if(StringUtils.isNotEmpty(request.getAtt2()) && null != request.getAtt1()) {
return false;
}
if(StringUtils.isNotEmpty(request.getAtt3()) && StringUtils.isNotEmpty(request.getAtt2())) {
return false;
}
//The below condition is to test that at least one request is present
if(StringUtils.isEmpty(request.getAtt3()) && null == request.getAtt1() && StringUtils.isEmpty(request.getAtt2())) {
return false;
}
return true;
}
如何使用Java 8 Optional使这段代码更易于编写和阅读?
为什么不算数?
int count = 0;
if(request.getAtt1() !=null) {
count++;
}
if(StringUtils.isNotEmpty(request.getAtt2())) {
count++;
}
if(StringUtils.isNotEmpty(request.getAtt3())) {
count++;
}
return count == 1;
使用Optional
的版本(不要使用,它只是为了好玩而添加)。
return Optional.ofNullable(request.getAtt1()).map(ignore -> 1).orElse(0)
+ Optional.ofNullable(request.getAtt2()).map(ignore -> 1).orElse(0)
+ Optional.ofNullable(request.getAtt3()).map(ignore -> 1).orElse(0)
== 1;
它也缺乏空字符串的检查。
这里没有必要使用Optional
。如果您只需要检查是否存在至少一个属性,则只需将其检查为:
public boolean validateAtLeastOneRequiredRequestParam(RequestBodyResource request) {
return request.getAtt1() != null
|| !StringUtils.isEmpty(request.getAtt3())
|| !StringUtils.isEmpty(request.getAtt2());
}
编辑1:对于一个完全一个检查,不是那么好,但比你当前的解决方案更可读(恕我直言):
public boolean validateExactlyOneRequiredRequestParam(RequestBodyResource request) {
long countPresentAttribute = Stream.of(request.getAtt2(), request.getAtt3())
.filter(StringUtils::isNotEmpty)
.count() +
Stream.of(request.getAtt1()).filter(Objects::nonNull).count();
return countPresentAttribute == 1;
}
编辑2:使用Optional
并摆脱对StringUtils
的外部依赖,你可以这样做:
public boolean validateExactlyOneRequiredRequestParam(RequestBodyResource request) {
long countPresentAttribute = Stream.of(
Optional.ofNullable(request.getAtt1()),
Optional.ofNullable(request.getAtt2()).filter(String::isEmpty),
Optional.ofNullable(request.getAtt3()).filter(String::isEmpty))
.filter(Optional::isPresent)
.count();
return countPresentAttribute == 1;
}