Consider the following class
Class RequestBodyResource {
private RequestVariable1 att1;
private String att2;
private String att3;
}
I have a method that should return false in 2 conditions
- If all the 3 attributes of the RequestBodyResource Object is null/empty
- If more than 1 attribute is populated at the same time
The code for the same is as
public boolean validateAtleastOneRequiredRequestParam(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;
}
How to use Java 8 Optional to make this code much easier to write and read?
Aucun commentaire:
Enregistrer un commentaire