-2

I want to do this code you have seen using ternary operation instead of if conditional blocks. Generally, is the use of the ternary operator always a good choice? In some places they say it is more readable and more flexible code to use the ternary operator instead of constantly using if conditional blocks.

     @Override
public ResponseEntity<? extends UserDetailResponse> getByPhoneNumberUserDetail(String phoneNumber) {
    UserDetail userDetail = userDetailRepository.findByPhoneNumber(phoneNumber);
    if (!userDetail.getPhoneNumber().equals(phoneNumber)) {
        return new ResponseEntity<>(new UserDetailResponse(MessageCase.COULDNT_FOUNDED_USER_DETAILS_SUCH_PHONE_NUMBER.getMessage(), 400), HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>(new UserDetailResponse(MessageCase.USER_DETAL_SUCESSFULLY_FOUNDED.getMessage(), 200), HttpStatus.OK);
}
  • 2
    The code doesn't appear to make much sense. Why do you have to check the phone again when you asked the `userDetailRepository` to give you a user with that phone already? Why would that condition `!userDetail.getPhoneNumber().equals(phoneNumber)` ever be true? – plalx Oct 17 '21 at 20:13
  • Firstly Checking if such a number exists in the database is the best choice for me. – zordu-nickim-agzivi-sikm Oct 17 '21 at 20:16
  • 1
    What I mean is that if `userDetail` is non-null then it should mean the phone matched, so you shouldn't have to check it again... – plalx Oct 17 '21 at 20:17
  • I understand what you mean, I will make changes, but now I'm wondering if I can do this using a ternary operation. – zordu-nickim-agzivi-sikm Oct 17 '21 at 20:18

1 Answers1

0
UserDetailResponse userDetailResponse = userDetail!=null && !userDetail.getPhoneNumber().equals(phoneNumber)  ? new UserDetailResponse(MessageCase.COULDNT_FOUNDED_USER_DETAILS_SUCH_PHONE_NUMBER.getMessage(), 400) : new UserDetailResponse(MessageCase.USER_DETAL_SUCESSFULLY_FOUNDED.getMessage(), 200);
responseEntity = new ResponseEntity<>(UserDetailResponse,UserDetailResponse.getStatus());
return responseEntity;

Implement getStatus in UserDetailResponse to fetch status code.