我想写越来越少的代码,我试图找到一种方法来防止崩溃。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它的工作,但我写太多的代码......我该怎么办?
方法2也应该工作。重新检查它。在java中如果第一部分是假的第二部分没有评估。 – Leonidos
重点不在于它不起作用,而在于它相对冗长 –