I’m writing a small piece of logic that checks if Facebook API retrieves the user email for me, if not, I’m setting the email from request parameter, or if that isn’t present either, I’m throwing an exception .
My question is that would you change anything aesthetically to make it look nicer based on Java 8 – Lambda conventions?
{
UserProfile newUser = new UserProfile(fbUser.getId());
if( null == fbUser.getEmail() ) { newUser.setEmail(userMail); }
if( null == newUser.getEmail() ) { throw new MissingServletRequestParameterException("email", "String"); }
newUser.setEmail(fbUser.getEmail());
newUser.setUsername(fbUser.getName());
newUser.setPassword(passwordEncoder.encode(fbReq.getAccessToken()));
newUser.setFirebaseToken(fbReq.getFirebaseToken());
newUser.setLanguage(HoopLocale.getById(locale.getLanguage().toLowerCase()).toString());
UserAccount acc = new UserAccount();
acc.setCurrency(currencyRepo.findById(CurrencyName.getById(fbReq.getCurrency()).getId())
.orElseThrow(() -> new ResourceNotFoundException("Currency id", "id", fbReq.getCurrency())));
newUser.setUserAccount(acc);
userRepository.save(newUser);
}
2
Answers
You can use
Optional
s but note that whether this looks “nicer” is arguable.You can use ifPresentOrElse (introduced in Java 9):
to replace this part of you code: