skip to Main Content

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


  1. You can use Optionals but note that whether this looks “nicer” is arguable.

    newUser.setEmail(
        Optional.ofNullable(fbUser.getEmail())
            .orElse(Optional.ofNullable(userMail)
            .orElseThrow(() -> new MissingServletRequestParameterException("email", "String")))
    );
    
    Login or Signup to reply.
  2. You can use ifPresentOrElse (introduced in Java 9):

    Optional.ofNullable(userMail)
    .ifPresentOrElse(newUser::setEmail, () -> {throw new MissingServletRequestParameterException("email", "String");});
    

    to replace this part of you code:

    if( null == fbUser.getEmail() ) {     newUser.setEmail(userMail); }
    if( null == newUser.getEmail() ) { throw new MissingServletRequestParameterException("email", "String"); }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search