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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With