我正在编写一小段逻辑,以检查Facebook API是否为我检索了用户电子邮件,否则,我是根据请求参数设置电子邮件,或者如果不存在,则抛出一个例外。 我的问题是,基于Java 8-Lambda约定,您会在美学上进行任何更改以使其看起来更好吗?
{
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);
}
答案 0 :(得分:1)
您可以使用ifPresentOrElse(在Java 9中引入):
Optional.ofNullable(userMail)
.ifPresentOrElse(newUser::setEmail, () -> {throw new MissingServletRequestParameterException("email", "String");});
替换您的代码的这一部分:
if( null == fbUser.getEmail() ) { newUser.setEmail(userMail); }
if( null == newUser.getEmail() ) { throw new MissingServletRequestParameterException("email", "String"); }
答案 1 :(得分:0)
您可以使用Optional
s,但请注意,这看起来是否“更精细”是有争议的。
newUser.setEmail(
Optional.ofNullable(fbUser.getEmail())
.orElse(Optional.ofNullable(userMail)
.orElseThrow(() -> new MissingServletRequestParameterException("email", "String")))
);