Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntelliJ/structural search: Remove useless methods that only call super method

In one of my Android projects (but not necessarily tied to Android) I have quite a few method calls that really do nothing but blow up the code and could be automatically removed. Examples:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
}

@Override
public void onDestroy() {
    super.onDestroy();
}

I couldn't find any inspections that help me in automatically removing these expressions, so I tried structural search. My attempt so far: I copied the template of 'annotated methods' and made 2 small changes.

  1. $Annotation$ changed to occurs=1, text=Override
  2. Added a $Statement$ variable with occurs=1

The template code:

class $Class$ {
    @$Annotation$( )
    $MethodType$ $MethodName$($ParameterType$ $ParameterName$) {
        $Statement$;
    }
}

So far, so good - it's only finding methods with a single line in the body. But now I want to explicitely search for exact statements calling the super method (kind of like a back reference to $MethodName$), but which also return the super value (when not void). Any ideas?

I believe this would be a really useful inspection that could be integrated into the main IntelliJ codebase as well. :-)

like image 487
mreichelt Avatar asked Jul 29 '15 21:07

mreichelt


2 Answers

So I recently found out that IntelliJ's 'Empty method' inspection actually looks for this. Simply:

Double Shift -> Run Inspection By Name -> Empty method

method only calls its super

The synopsis is 'Method only calls its super', but the inspection actually looks for more than just this, for example:

  • The method and all its derivables are empty
  • All implementations of this method are empty
  • The method is empty
  • Empty method overrides empty method

Depending on your situation it might find more than you want - and the refactoring tried to remove more than I actually wanted. But with a quick manual review you should be good to go. :-)

like image 121
mreichelt Avatar answered Oct 31 '22 13:10

mreichelt


Using Structural Search you will have to use two separate searches. One for finding methods with void return type:

class $Class$ {
    $MethodType$ $MethodName$($ParameterType$ $ParameterName$) {
        super.$MethodName$($ParameterName$);
    }
}

and a second for methods which return a value:

class $Class$ {
    $MethodType$ $MethodName$($ParameterType$ $ParameterName$) {
        return super.$MethodName$($ParameterName$);
    }
}

Specifying the @Override annotation is unnecessary in this case.

like image 22
Bas Leijdekkers Avatar answered Oct 31 '22 13:10

Bas Leijdekkers