Java如何防止null对象异常

时间:2013-10-23 14:01:04

标签: java exception

我正在尝试编写越来越少的代码,我正试图找到一种方法来防止崩溃。

我遇到的一个例子是:

public class MyClass
{
   private User user;

   public MyClass()
   {
       // Get user from another class
       // Another thread, user can be null for couple of seconds or minutes
       // Asynchronous call
       user = AnotherClass.getUser();

       // start method
       go();
   }

   private void go()
   {
      // Method 1
      // Program it is crashing if user is null
      if (user.getId() == 155)
      {
         // TO DO
      }
      else
      {
         System.out.println("User is NOT 155 !");
      }

      // Method 2
      // Program still crashes if user is null
      if (user != null && user.getId() == 155)
      {
         // To do
      }
      else
      {
         System.out.println("user is not 155");
      }

      // Method 3
      // Program wont crash, but I write much more code !
      if (user != null)
      {
         if (user.getId() == 155)
         {
            // To do
         }
         else
         {
            System.out.println("User is not 155 !");
         }
      }
      else
      {
          System.out.println("User is not 155 !");
      }
   }
}

正如你所看到的,方法3它正在工作,但我正在编写更多代码......我该怎么办?

3 个答案:

答案 0 :(得分:2)

首选Short-circuit evaluation,即方法2。

  

AND 函数的第一个参数评估为 false 时,整体值必须为 false ;

      if (user != null && user.getId() == 155)
      {
         // To do
      }
      else
      {
         System.out.println("user is not 155");
      }

这是最优选和可读的代码。

你遇到的错误是method2崩溃和method3有效。在上面的代码中user != null只执行user.getId() == 155

答案 1 :(得分:1)

为什么不在这里使用null object pattern,所以不是将user设置为null,而是将其设置为User对象的特殊“null”情况(实现)?

e.g。

user = AnotherClass.getUser();
if (user == null) {
   user = new NullUser();
}

(理想情况下,AnotherClass.getUser()会在内部进行空检查)

在这种情况下

user.getId()

可以返回一个特殊值(-1?),它永远不会等同于有效的用户ID。因此,您的代码将始终如下:

if (user.getId() == 155)

同样适用于User对象上的其他方法。

答案 2 :(得分:1)

这句话必须是在这个声明开始的块内:

if (user != null && user.getId() == 155)

这在逻辑上与方法3完全相同。当JVM看到user为空时,它应该停止评估它。

我会说,虽然我在JVM 1.3上遇到过类似的问题,但如果您使用的是真正旧的JVM,那么就可以了。