0

I am doing a null check using Optional.ofNullable() for an API response where all the fields are optional (for lack of a better word), but we want to map the ones that are present, which may differ on each response payload.

Optional.ofNullable(details.getBadResponse()).map(property -> property.getResponseStatus()).ifPresent(property -> {
    responseData.setRawResponseCode(property.getResponseStatus());
});
Optional.ofNullable(details.getBadResponse()).map(property -> property.getErrorMessage()).ifPresent(property -> {
    responseData.setResponseMessage(property.getErrorMessage());
});
Optional.ofNullable(details.getBadResponse()).map(property -> property.getErrorReason()).ifPresent(property -> {
    responseData.setResponseCode(property.getErrorReason(), "serviceError");
});
Optional.ofNullable(details.getBadResponse()).map(property -> property.getId()).ifPresent(property -> {
    responseData.setRecordId(StringUtils.defaultString(property.getId(), StringUtils.EMPTY));
});

Is it possible to combine these statements into one Optional.ofNullable check on the details object (where details is the response object) to have the code be more clean?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 3
    Erm ... `Optional<...> badResponse = Optional.ofNullable(details.getBadResponse());`. Ercetera. – Stephen C Mar 08 '23 at 00:28
  • 1
    Make it all statement != clean – Stephen C Mar 08 '23 at 00:29
  • 3
    In addition to @StephenC's suggestion, I'd add that the simplest thing here would just be `if (details.getBadResponse() != null) { var badResponse = details.getBadResponse(); ... }`. Not every nullable reference calls for `Optional`. Nulls are a way of life in Java; embrace them, and the code will often be cleaner. – yshavit Mar 08 '23 at 00:31
  • 1
    Yea ... that's a better idea / approach. – Stephen C Mar 08 '23 at 00:35
  • 1
    This code makes no sense. You are calling methods (`getResponseStatus()`, `getErrorMessage()`, `getErrorReason()`, `getId()`), followed by calling exactly the same methods on the result of those methods. Maybe, you should stop your habit of calling every variable “`property`”, regardless of its actual purpose and type. – Holger Mar 10 '23 at 11:26
  • the bad response is the json response object, where the fields present can be null, or present. I want to avoid an NPE by mandating all the fields be present. – William Johnson Mar 10 '23 at 21:15
  • 1
    Don’t try to explain what was understood. Just try to compile the code that you have posted here. – Holger Mar 16 '23 at 15:32

0 Answers0