mreichelt mreichelt - 18 days ago 8
Android Question

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

Answer

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

Comments