I have the following piece of code and I would like to see what different approaches would be to solve that in a more elegant way.
The thing is that I don't know whether is better to have the null checks or the try/catch block there or maybe the code below should not happen in the first place. Maybe one can give another solution so that I can get the thumb URL from a images list that is set on a people object without having to check for null on each getter call.
if (people.getImages() != null && people.getImages().size() > 0 && people.getImages().get(0).getUrl() != null) {
Url thumbUrl = people.getImages().get(0).getUrl().getThumb();
// do something with the thumbUrl
}
Or I can have:
try {
Url thumbUrl = people.getImages().get(0).getUrl().getThumb();
// do something with the thumbUrl
} catch (Exception e) {
// handle the null pointer exception
}
EDIT
For more information, I am interested more in knowing if there any other ways to avoid calling getter methods one after another until I get my desired data from an object and if the above code is good enough anyway.
The code works ok in both cases but I don't like to have the multiple null checks in that if statement and also catching exceptions is not a good solution either.
The getImages()
method returns a list of Image
objects and getThumb()
returns an Url
object that I need in order to fetch an image over the internet.
people.getImages
? what isgetThumb
? we can't review this code, there isn't enough information. \$\endgroup\$ – Malachi♦ Jul 18 '14 at 15:18