Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java calling methods on instance variable

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?

like image 635
adi Avatar asked Dec 02 '22 22:12

adi


2 Answers

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.

like image 104
Jon Taylor Avatar answered Dec 14 '22 14:12

Jon Taylor


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
}
like image 22
codebox Avatar answered Dec 14 '22 14:12

codebox