◎ Optional
- Java 8 부터 지원
- null이 올 수 있는 값을 감싸는 Wrapper 클래스
- NPE(NullPointerException)을 방지하기 위해 사용
- 해당 객체가 null 인지 아닌지 판단하기 용이
- null 일때 예외를 발생시키거나 기본값을 설정시켜줄 수 있다.
◎ Optional의 장점
- 해당 객체가 null 일지 아닐지 모를 때, if문을 사용하지 않고 표현가능함
◎ Optional 생성
Optional<String> optional = Optional.empty();
Optional<String> optional = Optional.of("MyName");
Optional<String> optional = Optional.ofNullable(getName());
◎ Optional instance method
Optional<String> optional = Optional.ofNullable(getName());
String name = optional.orElse("default");
String name = optional.orElseThrow(() -> new IlligalArgsException());
String nameNullable = optional.get();
boolean isNotNull = optional.isPresent();
◎ Optional 실사용 예시
public class Member {
private long memberId;
private String email;
private String password;
private String displayName;
private String image;
private String location;
private String memberTitle;
private String aboutMe;
public void updateMember(Member member) {
this.image = Optional.ofNullable(member.image).orElse(this.image);
this.displayName = Optional.ofNullable(member.displayName).orElse(this.displayName);
this.location = Optional.ofNullable(member.location).orElse(this.location);
this.memberTitle = Optional.ofNullable(member.memberTitle).orElse(this.memberTitle);
this.aboutMe = Optional.ofNullable(member.aboutMe).orElse(this.aboutMe);
}
}
@RequiredArgsConstructor
public class MemberServiceImpl{
private final MemberRepository memberRepository;
...
public Member findMember(long memberId) {
return findVerifiedMember(memberId);
}
private Member findVerifiedMember(long memberId){
return memberRepository.findById(memberId).orElseThrow(() ->
new BusinessLogicException(ExceptionCode.MEMBER_NOT_FOUND));
}
private void findMemberByEmailExpectNull(String email){
memberRepository.findByEmail(email)
.ifPresent(member -> {throw new BusinessLogicException(ExceptionCode.ALREADY_EXIST_EMAIL);});
}
private Member findMemberByEmailExpectExist(String email){
return memberRepository.findByEmail(email)
.orElseThrow(() -> new BusinessLogicException(ExceptionCode.MEMBER_NOT_FOUND));
}
}
@Test
void findMemberTest() {
Member expected = MEMBER_STUB;
given(repository.findById(1L)).willReturn(Optional.of(expected));
Member result = memberService.findMember(1L);
assertThat(result).usingRecursiveComparison().isEqualTo(expected);
}
◎ 참고 자료