Java calling methods on instance variable
coding-style, java
Solution
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.
Problem
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?