Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting precondition for a overriden function #6758

Open
gunjanaggarwal opened this issue Aug 12, 2024 · 0 comments
Open

Setting precondition for a overriden function #6758

gunjanaggarwal opened this issue Aug 12, 2024 · 0 comments

Comments

@gunjanaggarwal
Copy link

I work on an Android App. I am trying to improve annotations used in our code to reduce NPEs. The code I am working has many instances where a subclass overrides a function in superclass and this function uses a @nullable or @MonotonicNonNull member variable of the subclass. Here is a make-up example

public abstract class AbstractViewFragment{
 
    public void onLoad(){
      // do something here	
    }
}

public class SpecificViewFragment implements AbstractViewFragments{
  @Nullable private Object cursor;
   @MonotonicNonNull 	protected Object viewDetail;
    protected Object webView;

    SpecificViewFragment(){
	webView = new Object(); 
     }
…

    @override
    public void onLoad(){
	if (viewDetail.isType1()){
           // do A 
        }else{
            //do B
        }
    }
}

Nullness checker throws an error for using viewDetail.isType1() method as possible and in most cases, such errors are suppressed using checkNotNull(“viewDetail”) at the beginning of the SpecificViewFragment.onLoad() method and has caused NPEs as the callee of this function didn’t make sure that viewDetail is non_null.

If we try to add RequiresNonNull(“viewDetails”) to SpecificViewFragment.onLoad() it throws the error below:

error: [contracts.precondition.override.invalid] Subclass precondition is stronger for `this.var` in `overriddenFuntion`

As I understand, based on behavioural subtyping, precondition cannot be strengthened in the subtype.

But using checkNotNull is not preventing NPEs in the code either and is neither a great way to tell developers that they should be thinking about viewDetails being null. What would be a better solution in such cases?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant