That is my first post on the DWTF. While i'm a fervent reader since 2010 I never posted before because lots of code I see here is so much better (erm... you see what I mean) than the code I see daily I don't think my contribution would be worth it... Until today...
I'm working since more than a week on a web application we just got back from one of our contractors. I should have been production ready two weeks ago but we quickly found the application was crippled of bugs and mis behavior so my bosses called me (and another pal) to patch/glue/sew/anythingelseyoucanimagine the application in order to make it work a much as we can.
It quickly turned the code (either Java or Javascript) was of very high WTF standards.
I'm just gonna share the last bit I found this morning which made me understand that I totally missed what Java8 really offered us since it has been publicly available. Shame on me.
This part of code is a OTP validation system. OTP is 6 digits long and is only valid for a couple of minutes.
public Boolean verifyOtpUserBOCode(OtpUserBODTO otpUserBODTO, String otp) {
// First some null tests...
if(Objects.isNull(otpUserBODTO)) {
log.info("otpUserBODTO NULL ");
return null;
}
OtpUserBO otpUserBO = otpUserBORepository.findOneByLogin(otpUserBODTO.getLogin());
if(Objects.isNull(otpUserBO)){
log.info("otpUserBO NULL ");
return null;
}
// Get duration from database and do nothing of it
RefParam refParam = refParamRepository.findOneByLibelleParam(Constantes.DURATION_OTP_CODE_IN_SECOND);
Long durationOtpCode = 0L;
if(!Objects.isNull(refParam)){
durationOtpCode = Long.parseLong(refParam.getValeurParam());
}
// another null check
ZonedDateTime dateCreationOtpCode = otpUserBO.getDateCreationOtpCode();
if(Objects.isNull(dateCreationOtpCode)){
log.info("dateCreationOtpCode NULL");
return null;
}
// Check if the OTP in DB is the same as the one passed in parameter
if(otp.equals(otpUserBO.getOtpCode()))
return true;
return false;
}
As you can see we are returning true/false/null, quite a standard tri-lean. You can also notice the good use of dateCreationOtpCode and durationOtpCode... Yes they are absolutely not checking the expiration time...
What is really ingenious here is how they handle the result !
Boolean resultFound = verifyOtpUserBOCode(otpUserBODTO, otpCode);
return Optional.ofNullable(resultFound)
.map(result -> new ResponseEntity<>(
result,
HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
Optional.ofNullable ! Damn that's really elegant ! Thanks Java 8 !