I have the following code which is adding somestrings to an arraylist. It will ever so often have an empty variable due to someone not filling it in correctly. I don’t own the usr object so I can’t modify it unfortunately. Is there a clean and easy way of just adding a default value if one of these values is empty? I don’t mind if its empty, but I don’t want the program to crash out!
results.add(usr.getName());
results.add(usr.getAbout());
results.add(usr.getBirthday());
results.add(usr.getEmail());
results.add(usr.getGender());
You just have to check if the values are null.
You can do this for each of the values. You can use a shorter syntax like
Though that requires calling getName twice, it shouldn’t matter since I assume that is just a simple getter.
Edit #1
If you don’t want to check for null on every check, you can use a reflection based solution. This example is groovy based, and while I do think it’s overkill for a few values, if you have a lot of values, it might make more sense.