5

I have a class TeamResponse used to form a JSON response. It has a handful of parameters, and one of them can be optional:

public TeamResponse(Team team, List<TeamSkillTemplateResponse> teamSkillTemplateResponses) {
    this.id = team.getId();
    this.name = team.getName();
    this.department = new DepartmentResponse(team.getDepartment());
    this.division = new DivisionResponse(team.getDepartment().getDivision());
    this.valueStream = team.getValueStream().map(ValueStreamResponse::new).orElseGet(null);
    this.skillTemplate =  teamSkillTemplateResponses;
}

I have actually two questions on this one: 1. Is it appropriate to return null in the response, if the value is not present? 2. Is it appropriate to return null THIS way? (method getTeam() returns Optional)

Thank you.

pkey
  • 97
  • 1
  • 2
  • 6
  • 9
    You don’t want `orElseGet(null)`; you probably want `orElse(null)`! `orElseGet` takes a supplier, and that supplier should not be null (though I think it’s allowed to _return_ `null`). – andrewf Oct 25 '19 at 14:03

2 Answers2

7
  1. yes it is. json output will be field not being present, or field null; it depends on json framework configuration. both kind of results are ok from json point of view. Difference only matters if talking about partial updates.
  2. no, you should use .orElse(null) not orElseGet (there you are passing a null supplier, not a null result value).
albert_nil
  • 1,648
  • 7
  • 9
0

In my opinion it is okay to return null if there is no value. The only other two options I see are not including the missing value at all in the JSON reply or using some default value which signifies the absence of a value.

Leaving out the value completely depends on the library you use for creating the actual JSON. AFAIK it is not possible to do this when using JAXB annotations. If you use Jackson it is possible though (see this answer).

The second option depends on whether there is a suitable default value. I would definitely go for this option if your value is an array. Instead of returning null I would return an empty array as this usually can be processed by clients without any special handling.

Christoph Böhme
  • 3,766
  • 1
  • 19
  • 29