Issue
I have this method:
public String updateShift(ShiftsDTO shiftsDTO){
Optional<Shifts> optionalPreUpdateShift = shiftsRepository.findById(shiftsDTO.getId());
if (optionalPreUpdateShift.isPresent()) {
if (!shiftsRepository.existsByShiftStartAndShiftEnd(shiftsDTO.getShiftStart(), shiftsDTO.getShiftEnd())) {
Shifts preUpdateShift = optionalPreUpdateShift.get();
shiftsMapper.mapShiftFromDto(shiftsDTO,preUpdateShift);
shiftsRepository.save(preUpdateShift);
return " Shift updated successfully";
} else {
throw new ShiftAlreadyExistsException("An existing shift already covers this period");
}
} else {
throw new ShiftNotFoundException("This shift doesn't exist");
}
}
This method is for updating shifts in a shop. I didn't use isPresent() before and now tried to implement it but the code looks incredibly dirty and unreadable. What are the correct ways to use Optional in such cases?
Solution
One way to keep yourself from indenting like this: Change your first line
Optional<Shifts> optionalPreUpdateShift = ShiftsRepository.findById(shiftsDTO.getId());
to instead unwrap the optional right away:
Shifts shifts = ShiftsRepository.findById(shiftsDTO.getId())
.orElseThrow(()-> new ShiftNotFoundException("This shift doesn't exist");
Answered By - hpr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.