简体   繁体   English

在Java中检查null的更好方法

[英]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. 但是通过这种方式,我要两次调用getContact服务,这对于应用程序来说是开销,这是检查空值的更好方法,因此我只需要调用一次服务即可。

do the if twice if两次

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. 不过,最好是,如果ID与批准的格式不匹配,则应该抛出IllegalArgumentException ,这是因为与没有有效ID的条目相比,这是一个不同的错误),并且应该使用Pattern.compile将该模式保存为常量字段,而不是(1)在每次调用时重新编译它,以及(2)将其隐藏为颂歌内部的魔术常数。

What about 关于什么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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