2013-10-23 51 views
0

我想写越来越少的代码,我试图找到一种方法来防止崩溃。Java如何防止空对象异常

一个例子,我曾经遇到过什么:

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它的工作,但我写太多的代码......我该怎么办?

+1

方法2也应该工作。重新检查它。在java中如果第一部分是假的第二部分没有评估。 – Leonidos

+0

重点不在于它不起作用,而在于它相对冗长 –

回答

1

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

例如

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

(理想AnotherClass.getUser()会做内部空校验)

在这种情况下

user.getId() 

可以返回一个特殊值(-1?),它绝不会等同于一个有效的用户标识。因此,您的代码将永远看起来像:

if (user.getId() == 155) 

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

+0

如果我编辑User类并添加一个默认值为-1的字段ID,该怎么办? private int id = -1;公共用户(/ * params * /){} –

+0

也许这也适合 –

1

它一定是被这句话开始的块里面的东西:

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

这在逻辑上是相同的方法3.当JVM看到的是user为null,则应该停止该评估。

我会说,虽然我在JVM 1.3中遇到过类似的情况,所以如果您使用的是真正旧的JVM,可能就是这样。

2

喜欢的方式Short-circuit evaluation,即方法2

AND函数的第一个参数的计算结果为,总体值必​​须为;

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

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

你的设想是错误的,method2崩溃和method3的作品。在上面的代码中,如果user != null那么只有user.getId() == 155执行。

+0

如果我交换这两个条件呢? if(user.getId()== 155 && user!= null)? –

+0

@ZbarceaChristian你最终会得到Null指针异常。如果交换这些条件,那么它就像'if(user.getId()== 155) {if(user!= null){}',这是没有意义的。 –