Ubaier Bhat Ubaier Bhat - 26 days ago 5
Android Question

Avoiding != null using a method in java

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.

Answer

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 {
     public show() {
         //does nothing
      }
    }

(2) Use the EmptyView in case of no view available:

   //other classes:
    private View getView(){
        if(viewAvailable) {
           return view;
        } else {
          EmptyView emptyView = new EmptyView();
            return emptyView;
        }  
    }

    public void showView(){
        getView().show();
    }

You can look at Wiki here more info & Java example.

It is a bad practice to return null from a method 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 in the answer from janos.