In my example below I want to avoid writing getView != null every time I want to use getView. To keep it cleaner I create a method hasView() which does the check for me. However I still get a warning. Is there any way around this?
import android.support.annotation.Nullable;
public void showView(){
if(hasView()){
getView().show(); // Shows warning Method invocation 'showLoading' may produce 'java.lang.NullPointerException'
}
}
boolean hasView(){
return getView() != null;
}
@Nullable
private View getView(){
return view;
}
I am using Android Studio/IntelliJ. I know that I can use @SuppressWarnings I have seen this question but this makes the code uglier.
I want to avoid writing getView != null every time I want to use getView ?
You can use Null Object pattern to avoid checking for != null
everywhere in the program, the code is shown below:
(1) Define an EmptyView Class
public EmptyView {
//Define a static emptyView, so that we can reuse the same object
public static final EmptyView emptyView = new EmptyView();
public show() {
//does nothing
}
}
(2) Use the EmptyView in case of no view available:
//other classes:
private View getView(){
if(viewAvailable) {
return view;
} else {
return EmptyView.emptyView;
}
}
public void showView(){
getView().show();
}
You can look at Wiki here more info & Java example.
When you return null
from various methods, they will potentially cause the NullPointerException
in the programs and will become very hard to debug in larger projects.
So, it is a bad practice to return null
from methods (& they should be avoided) and that is the reason Spring API generally return empty list
/set
objects (instead of null
) while trying to retrieve data from DAO
/Repository
classes (like EmptyView
object as explained above).
P.S.: This option works with and without Java8.
If you are using Java8, then prefer to do with Optional
as given in the answer from @janos
You might be interested in using an Optional
, added in API level 24 of Android, for example:
private Optional<View> getView() {
return Optional.ofNullable(view);
}
public void showView() {
getView().ifPresent(View::show);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With