Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of StatementWithEmptyBody?

when I created the drawer bar in Android Studio for my project, in the code for the select items put the next:

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {

But what is the use of this annotation?

like image 699
Tlaloc-ES Avatar asked Feb 05 '19 11:02

Tlaloc-ES


4 Answers

Warning itself explains meaning.

return type of onNavigationItemSelected is boolean. and we need to return any boolean value.

If there is if condition in onNavigationItemSelected and not returned then @SuppressWarnings("StatementWithEmptyBody") need to add.

Example:

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.xyz) {
       // you should return boolean value here.
    }
    return false;
}

In example we are returning false by-default. and we haven't return any value in

if (id == R.id.xyz) condition.

You can clearly have a look at warning.

suppress warning

like image 74
Rumit Patel Avatar answered Nov 13 '22 14:11

Rumit Patel


In case, if you have not inserted any code in that method, the annotation will make sure that no warnings are generated for that method.

like image 45
Fatema Khuzaima Sagar Avatar answered Nov 13 '22 14:11

Fatema Khuzaima Sagar


When you have a statement with no code inside of the curly brackets, Android Studio will give a warning about this. The annotation suppresses this warning in method having this annotation.

Example of statement with empty body (the body of the "else" part is empty):

if (something) {
    doThis();
} else {

}

These warnings are useful to let you double check if you didn't forget to code something. Only turn them off (with the annotation) when you have a good reason to do so.

like image 3
Wouter Van der Schraelen Avatar answered Nov 13 '22 16:11

Wouter Van der Schraelen


This guards against things like:

if(condition)
{
 //empty body
}

OR

private void methodeName(){
  //empty body
}

The error raised forces you to explicitly put the empty {}

I should probably clarify that suppressing a warning that does have merit is a silly thing to do. A clean bill of health that you obtained by cheating is obviously worth nothing. Given the choice, you should always fix the problem the compiler noticed rather than just close your eyes to it. However, there are areas in which the compiler cannot be sure whether something will be a problem or not (Java's generics are one such area), and there the better choice is to review each such instance and then suppress the warning in this specific place rather than to switch off this class of warning altogether and potentially miss a genuine one.

like image 3
Praveen Avatar answered Nov 13 '22 14:11

Praveen