7

A friend of me advices me to initialise DTO fields of type (ArrayList) and only of type ArrayList in DTOs like this to avoid NullPointerException

public class fooDto {
    private SomeClasse someClasse = new SomeClasse();
    private ArrayList<Bar> bars = new ArrayList();
}

should we do his ? and is it a good practice

in other way , should we use "= new SomeClasse()" or not ?

KaderLAB
  • 348
  • 3
  • 9

3 Answers3

6

With List, definitelly yes (it is unfotunatelly quite common to try to put an item to a null list). However about someClasse, well it depends. If you're trying to avoid at all cost annoying null check than perhaps it is ok. However if someClasse is an optional field than why should it be initialised? On the other hand if it should not be null than perhaps it is for the best to let this exception be thrown . After all it is easy to find a cause of it, otherwise you would be stack with analisis was it actually set by something to empty value or was it empty because of some mistake?

To sumarise in my opinion you gain more by not initialising it. You always could use some preconditions to easy check null value and throw more civilized exception.

pokemzok
  • 1,659
  • 1
  • 19
  • 29
1

I think for a Collection it would make sense to initialize it. When it comes to other properties like your SomeClass example this might differ per case.

You could use the Null Object design pattern, which is a pattern that should avoid having a real null value by accident.

Albert Bos
  • 2,012
  • 1
  • 15
  • 26
  • It is not a good practice to use Optional as fields. Example source here: https://stackoverflow.com/questions/31922866/why-should-java-8s-optional-not-be-used-in-arguments – pokemzok Sep 15 '17 at 19:58
  • 1
    @pokemzok makes sense for data structures, would make more sense in services/repositories. removed it from my comment. – Albert Bos Sep 15 '17 at 20:11
0

Depends how you are using these DTO's.

It make sense to do when you have to manually copy data from domain object to DTO.

Otherwise, if you're using a library for that, like ModelMapper, beanutils or something similar it looks a bit redundant to me, since such tools can handle nulls and all this kind of stuff.

Bohdan Levchenko
  • 3,411
  • 2
  • 24
  • 28