0

I have confusing (lack of comprehension) trying to translate some part of my code to Optional on Java 8.

First example mock Code

    private void privateMethodOne(CustomRequesDto customRequesDto) {

        // Some lines of code

        ResponseEntity<CustomResponseDto> responseEntity;
        try {
            responseEntity = callWebClientRequestOne();
        } catch (Exception e) {
            RuntimeException ex = new CustomClientException(customRequesDto, e.getMessage());
            log.error(ex.getMessage());
            throw ex;
        }


        if (responseEntity.getBody() == null) {
            throw new CustomResponseException("myMessage");
        }
        CustomResponseDto customResponseDto = responseEntity.getBody();
        return Optional.ofNullable(customResponseDto).map(CustomResponseDto::getProperty).orElse(null);

    }

In the First example mock Code, I would like to reduce this lines in a single line, using Optional (if it is possible)

        if (responseEntity.getBody() == null) {
            throw new CustomResponseException("myMessage");
        }
        CustomResponseDto customResponseDto = responseEntity.getBody();
        return Optional.ofNullable(customResponseDto).map(CustomResponseDto::getProperty).orElse(null);

How to do the same in a Single line?

Second example mock Code

    private void privateMethodTwo(CustomRequesDto customRequesDto) {

        // Some lines of code

        ResponseEntity<byte[]> responseEntity = null;
        try {
            responseEntity = callWebClientRequestTwo();
        } catch (Exception e) {
            mapExceptions.put(customRequesDto, e.getMessage());
        }

        try {
            if (responseEntity != null && responseEntity.getBody() == null) {
                throw new CustomResponseException("myMessage");
            }
        } catch (Exception e) {
            mapExceptions.put(someObject, e.getMessage());
        }

        // continue the executions
    }

Second example mock Code, I would like to reduce this lines in a single line, using Optional (if it is possible)

        try {
            if (responseEntity != null && responseEntity.getBody() == null) {
                throw new CustomResponseException("myMessage");
            }
        } catch (Exception e) {
            mapExceptions.put(someObject, e.getMessage());
        }

How to perform the same in a Single line?

2
  • I would like to reduce this lines in a single line Why? Use an appropriate amount of lines to write clear, understandable code. Cramming as much code into as few lines as possible is bad, not good. Commented Jan 19, 2023 at 23:22
  • Only, I'd like to improve my understanding by looking at how Optional would be used under certain conditions. Because for me is not clear. Commented Jan 20, 2023 at 0:03

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.