0

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.

6
  • Put it in a variable? Furthermore, (1) if your matcher fails, you should probably be throwing IllegalArgumentException, and (2) you should precompile that pattern instead of using it inline and compiling on every call. Commented May 8, 2014 at 8:55
  • good question... dont understand the downvotes too. maybe he is a beginner?
    – nano_nano
    Commented May 8, 2014 at 9:02
  • Not sure what's wrong with people over SO nowadays; simply downvote even if it doesn't make any sense.
    – Rahul
    Commented May 8, 2014 at 9:03
  • It's a valid programming question as far as I can tell Commented May 8, 2014 at 9:06
  • I downvoted and for me this question, even from a beginner, just reveal you have not checked this site or any other help prior to ask your question on SO.
    – benzonico
    Commented May 8, 2014 at 9:11

3 Answers 3

4
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.

0
4

do the if twice

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

What about

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.