Best way to close and shutdown objects in onDestroy
Inside the onDestroy method, whats the correct way to determine if an object was actually initialized before trying to close it/shut it down/etc.
For example, which is better:
protected void onDestroy()
{
if(tts != null)
{
tts.shutdown();
}
if(dbWord != null)
{
dbWord.close(开发者_StackOverflow中文版);
}
super.onDestroy();
}
or this:
protected void onDestroy()
{
if(tts instanceof null)
{
tts.shutdown();
}
if(dbWord instanceof TextToSpeech)
{
dbWord.close();
}
super.onDestroy();
}
Use != instead of instanceOf to check if a variable was initialized. instanceOf performs additional type checking which you do not need in this case.
Use !=
, don't use instanceOf
. When you declare an object, it's already an instance of some class, even it's not initialized, NULL certainly.
The first one of yours is correct way to handle.
精彩评论