简体   繁体   中英

Better way to check for null in Java

I am checking for null value from the service which involves database transaction like this

if(!id.matches("-?\\d+(\\.\\d+)?") || contactService.getContact(id) == null){ 
      throw new ResourceNotFoundException();
  }
Contact contact = contactService.getContact(id);

But by this way I am calling getContact service twice and its a overhead for the application , any better way to check for null value, so that I just need to call my service once.

do the if twice

if(!id.matches("-?\\d+(\\.\\d+)?")){ 
      throw new ResourceNotFoundException();
  }
Contact contact = contactService.getContact(id);
if(contact == null){ 
      throw new ResourceNotFoundException();
  }
Contact contact;

if(!id.matches("-?\\d+(\\.\\d+)?") || (contact = contactService.getContact(id)) == null){ 
    throw new ResourceNotFoundException();
}

Preferably, though, you should throw IllegalArgumentException instead if the ID doesn't match the approved format (since that's a different error than if there's no entry for a valid ID), and you should use Pattern.compile to save that pattern as a constant field instead of (1) recompiling it on every call and (2) hiding it as a magic constant deep inside your ode.

What about

Contact contact = contactService.getContact(id);
if(!id.matches("-?\\d+(\\.\\d+)?") || contact == null){ 
    throw new ResourceNotFoundException();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM