Avoidance! = Null using method in java

In my example below, I want to avoid writing getView! = Null every time I want to use getView. To make it cleaner, I create a hasView () method that does the validation 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 I can use @SuppressWarnings I saw this question , but it makes the code more ugly.

+4
source share
2 answers

I want to avoid getting getView! = Null every time I want to use getView?

Null Object, != null , :

(1) EmptyView

   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) EmptyView :

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

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

Wiki Java.

null , NullPointerException .

, null (& ), API Spring list/set ( null) DAO/Repository (, EmptyView, ).

P.S.: Java8 . Java8, Optional @janos

+7

Optional, API 24 Android, :

private Optional<View> getView() {
    return Optional.ofNullable(view);
}

public void showView() {
    getView().ifPresent(View::show);
}
+4

Source: https://habr.com/ru/post/1660599/


All Articles