Subodh Joshi
Subodh Joshi

Reputation: 13512

Null-safe Method invocation Java7

I want to get details about this feature of Java7 like this code

public String getPostcode(Person person)
{
    if (person != null)
    {
        Address address = person.getAddress();
        if (address != null)
        {
            return address.getPostcode();
        }
    }
    return null;
}

Can be do something like this

public String getPostcode(Person person)
{
    return person?.getAddress()?.getPostcode();
}

But frankly its not much clear to me.Please explain?

Upvotes: 11

Views: 10897

Answers (4)

radiantRazor
radiantRazor

Reputation: 489

If you want to avoid calling getAddress twice, you can do this:

Address address;
if (person != null && (address = person.getAddress()) != null){
      return address.getPostCode();
}

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213321

Null-safe method invocation was proposed for Java 7 as a part of Project Coin, but it didn't make it to final release.

See all the proposed features, and what all finally got selected here - https://wikis.oracle.com/display/ProjectCoin/2009ProposalsTOC


As far as simplifying that method is concerned, you can do a little bit change:

public String getPostcode(Person person) {

    if (person == null) return null;
    Address address = person.getAddress();
    return address != null ? address.getPostcode() : null;
}

I don't think you can get any concise and clearer than this. IMHO, trying to merge that code into a single line, will only make the code less clear and less readable.

Upvotes: 14

Eldar
Eldar

Reputation: 5237

It should work for you:

public String getPostcode(Person person) {
    return person != null && person.getAddress() != null ? person.getAddress().getPostcode() : null;
}

Also check this thread: Avoiding != null statements

Upvotes: 0

Kon
Kon

Reputation: 10810

If I understand your question correctly and you want to make the code shorter, you could take advantage of short-circuit operators by writing:

if (person != null && person.getAddress() != null)
    return person.getAddress().getPostCode();

The second condition won't be checked if the first is false because the && operator short-circuits the logic when it encounters the first false.

Upvotes: 1

Related Questions