There are a lot of cases when you are supposed to do a mapping exercise for incoming DTO into another Object. Sending empty collections instead of null can be a waste of traffic, and even nulls are excluded by using
mapper.setSerializationInclusion(Include.NON_NULL);
or even mapper.setSerializationInclusion(Include.NON_EMPTY);
That said, if you need to do something like:
Collection<Dto> dtos = null;
for(Dto dto: dtos) {
//doSomething
}
You have to protect with if
(ok, but I prefer another way) or stick to NullObject idiom(good):
Collection<Dto> safeDtos = Optional.ofNullable(dtos).orElse(Collections.emptyList());
for(Dto dto: safeDtos) {
//doSomething
}
Or the same but for streams:
Optional.ofNullable(dtos).orElse(Collections.emptyList()).stream()
.map(this::doSomething)
.collect(Collectors.toList());
Also, try not to leak DTOs in any downstream code except that mapping exercise. You should have a border of protection between DTO and the rest of your code.
DTO -> Mapping -> Domain Object(or another intermediate object which is NPE save and maybe has enums instead of strings, etc) -> Rest of your code.
myList
is notnull
then where you need to check whethermyList
size is greater than 0? What I mean here is that if your list is not null, then it must have size and lists can't have negative sizes, so I thinkmyList.size() > 0
is not necessary in your case, unless it is initialized. – Amir Apr 08 '14 at 09:23