Tushar
Tushar

Reputation: 1176

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.

Upvotes: 0

Views: 154

Answers (3)

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.

Upvotes: 4

Uwe Allner
Uwe Allner

Reputation: 3467

What about

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

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44824

do the if twice

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

Upvotes: 4

Related Questions