Null-safe Method invocation Java7

风格不统一 提交于 2019-11-30 09:11:01

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.

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.

Eldar Agalarov

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

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

Address address;
if (person != null && (address = person.getAddress()) != null){
      return address.getPostCode();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!