6

I'm using Jackson JSON parser. I have simple data transfer object which should be returned via REST service.

public class PersonDto {

  private String name;
  private Integer age; // int?

  public PersonDto(String name, Integer age) {
      this.name = name;
      this.age = age;
  }

  public String getName() {
      return this.name;
  }

  public Integer getAge() {
      return this.age;
  }
}

Should I favor wrapper classes over primitive types as fields in such case? Which of these approaches has more advantages, except that wrapper is nullable?

Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
k13i
  • 4,011
  • 3
  • 35
  • 63

2 Answers2

9

Wrapper class: java.lang.Integer

Pros:

  • Allows null value, therefore giving the chance to the user to leave a blank / non-specified field
  • Fast when values are between -128 and 127, as it uses its internal cache instead of creating new objects

  • Integer::valueOf for parsing String's

Cons:

  • Immutable: if you have to reset the value (e.g: because it exceeded a certain range), you'll have to re-create a whole new Integer instance.

  • Slower calculation performance

  • java.lang.Integer is a reference to an instance. Each calculation will recreate a whole new Object


Primitive type: int

Pros:

  • Mutable (as long as non-final, and a setter is provided): easily allows: this.age = age > MAX_AGE ? blabla : age;

  • primitive types calculations are faster

  • Integer::parseInt for parsing String's

Cons:

  • Non-selected values will be automatically set to 0; this may create confusion on whether the user selected 0 as value, or did not select anything

It seems the only advantage of java.lang.Integer is the blank / null value.

Also, in cases where a wrapper is needed, e.g:

List<Integer> myList;

you can directly add an unboxed value myList.add(2); which is interpreted by the compiler as myList.add(Integer.valueOf(2));

payloc91
  • 3,724
  • 1
  • 17
  • 45
2

I found using wrapper in DTO's beneficial. With Jackson, for nullable fields you can set @JsonInclude(JsonInclude.Include.NON_NULL) on top of the DTO object and reduce the number of data sent via network (null fields will not be present in resulting JSON), thus resolving ambiguity if value is 0 or not present, telling the front-end that no node is present and hence no processing/displaying data is needed. For non-nullable numeric data, primitive works well. Also, for floating-point data that are not supposed to be used in front-end in arithmetic calculations, one can use String with rounding performed on server-side. I saw this technique multiple times in REST API's.

    DecimalFormat df = new DecimalFormat("#.####");
    df.setRoundingMode(RoundingMode.CEILING);
    System.out.println(df.format(d));
Andreas Gelever
  • 1,736
  • 3
  • 19
  • 25