• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

Optional 처리방법 문의

21.06.29 08:59 작성 조회수 238

0

isPresent 와 orElseThrow 의 차이점에 대해 문의 드립니다.

Optional 을 공부하다보니 에러처리를 동시에 하는 함수가 있어서 사용해보았습니다.

제가 생각할때는 변수에 저장하지 않고 바로 사용하는 부분이 장점 같았는데, 두 방식에서 내부동작의 차이점이 있는지 궁금합니다.

        Optional<UserfindById = userRepository.findById(id);

        if (! findById.isPresent()) {
            throw new UserNotFoundException(id);
       }

userRepository.findById(id).orElseThrow(() -> new UserNotFoundException(id))

답변 1

답변을 작성해보세요.

1

안녕하세요, 이도원입니다. 

Optional을 사용하면 Null 체크 작업을 줄입 수 있습니다. 값이 있으면 원하는 객체로 받고 없으면 Exception처리를 하는 패턴을 사용하게 되어 불필요한 Null 체크를 하지 않도록 할 수 있습니다. 

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).

말씀하신것처럼, 변수에 저장하지 않고 사용할 수 있도고 생각할 수도 있으나, 반환되어 오는 값의 처리를 간소화 하기위해 사용하게 됩니다.  orElseThrow() 메소드는 Null일 경우에 대해 특정 예외를 반환할 수 있도록 하며, orElseGet() 메소드를 통해 특정 객체르 생성하여 기본 값처럼 반환할 수도 있습니다.    

Optional을 사용하여, 아래와 같은 원하는 형태의 예외를 던질 수도 있고, Null일 경우 지정된 값을 반환할 수도 있습니다. 

#1) return userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("No such data");

#2) return userRepository.findById(id).orElseGet(User::new);

감사합니다. 

    

Jack님의 프로필

Jack

질문자

2021.07.08

답변 감사합니다.