我想寫越來越少的代碼,我試圖找到一種方法來防止崩潰。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
重點不在於它不起作用,而在於它相對冗長 –