Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize fileds in DTO

Tags:

java

dto

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 ?

like image 215
KaderLAB Avatar asked Sep 15 '17 19:09

KaderLAB


2 Answers

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.

like image 185
pokemzok Avatar answered Nov 01 '22 17:11

pokemzok


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.

like image 45
Albert Bos Avatar answered Nov 01 '22 18:11

Albert Bos