Java | Spring

[Java][Java 8, Java 10] Optional 활용하기, orElseThrow

binaryJournalist 2020. 11. 26. 16:00
반응형

 

 

orElseGet 에 이어 orElseThrow 를 소개한다.

 

 

내가 쓰임에 맞게 사용한지는 모르겠지만 일단 설명은 해보겠다. (컨펌 전임)

 

 

나의 이전 코드는 이렇다.

 

// ServiceImpl

@Transactional
@Override
public Entity updateEntity(Entity updateEntity) {
	
    Optional<Entity> optEntity = entityRepository.findById(updateEntity.getEntityId());
    if(optEntity.isEmpty()) {
        return null;
    }
    updateEntity.setBlahBlah(something);
    
    return entityRepository.save(updateEntity);
}

 

이렇게 되면 그냥 NullPointerException 위험에 노출되기 때문에 Optional 을 사용한 의미가 없다.

 

 

바꾼 코드는 이렇다.

 

 

// ServiceImpl

@Transactional
@Override
public Entity updateEntity(Entity updateEntity) {
	
    Optional<Entity> optEntity = entityRepository.findById(updateEntity.getEntityId());
    
    optEntity.orElseThrow()
    
    updateEntity.setBlahBlah(something);
    
    return entityRepository.save(updateEntity);
}

 

 

Java 8 에서는 orElseThrow 가

 

optEntity.orElseThrow(() -> new Exception())

optEntity.orElseThrow(Exception::new)

 

이처럼 인자값을 받아야 했지만

 

 

Java 10부터는

 

인자값 없는 orElseThrow() 도 가능하게 되었다.

 

 

사실 바꾼 코드에서도 entityId 가 updateEntity에 확실히 있다는 전제가 깔려있어야 위 코드가 실행되는데 뭔가 찜찜하다.

 

 

------- 2021.04.06 orElseThrow 관련 수정

 

 

 

이전까지 내가 작성했던 코드는

 

public void methodSomething(Param param) {
	Entity entity = entityRepository.findById(param.getEntityId()).orElseGet(Entity::new);
    if (Entity.getEntityId() == null) {
    	throw Exception.createError("에러메시자");
    }
    
    // 코드 이어 작성
}

 

이런 식이었다.

 

사실상 orElseThrow 로 한 줄로 작성 가능한 코드를 어떻게 이어쓸지 몰라 저렇게 코드르 낭비하며 사용하고 있었다.

 

 

근데 이번에 터득하게 되어 블로그에 기록을 남기려 한다. (별 거 아니지만)

 

 

public void methodSomething(Param param) {
	entityRepository.findById(param.getEntityId()).orElseThrow(() -> Exception.createError("에러메시지"));
}

 

 

findById를 안 쓰는 경우와 리스트로 값을 받는 경우 이렇게 쓸 수 있다.

 

public void methodSomethingForList(Param param) {
	List<Entity> entityList = Optional
    	.ofNullable(entityRepository.findAllByParam(param))
        .orElseThrow(() -> Exception.createError("에러메시지"));
}
반응형