Got two ways:
String salary = company.getPerson(id).getData().getSalary(); String postcode = company.getPerson(id).getData().getPostCode();
or
Data data = company.getPerson(id).getData(); String salary = data.getSalary(); String postcode = data.getPostCode();
Which is the preferred way and why? Any benefits apart from readability?
Id actually prefer a third option in case the person does not exist
Person person = company.getPerson(id);
if(person != null) {
Data data = person.getData();
if(data != null) {
String salary = data.getSalary();
String postcode = data.getPostCode();
}
}
It depends whether there may be null values or not. If you can guarantee there will be no null values then you can eliminate some/all of the null checks.
As another user pointed out in the comment below there may be a case where none of the method calls can return null in which case unless performance is an issue it would really be down to personal preference in my opinion.
I would probably still prefer to seperate them out into seperate calls as I have, even without the null checks.
If there is any chance that the intermediate variable may be null, then you should use the second option, together with a null check
Data data = company.getPerson(id).getData();
if (data != null){
String salary = data.getSalary();
String postcode = data.getPostCode();
// other code here
}
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