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

In one of my Android projects (but not necessarily bound to Android), I have quite a few method calls that really do nothing but explode the code and can be automatically deleted. 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 could not find any checks that would help me automatically remove these expressions, so I tried a structural search. My attempt so far: I copied the "annotated methods" template and made 2 small changes.

  • $ Annotations $ changed to happens = 1, text = Override
  • Added $ Statement $ with with = 1 variable

Template Code:

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

So far so good - he only found methods with one line in the body. But now I want to explicitly look for exact operators that call the super method (like a back reference to $ MethodName $), but which also return a super value (if not empty). Any ideas?

I believe that this will be a really useful inspection, which can also be integrated into the IntelliJ core code base. :-)

+7
java android intellij-idea android-studio structural-search
source share
2 answers

So, I recently found out that IntelliJ's "Empty Method" inspection is really looking for this. Just:

Double shift -> Run check by name -> Empty method

the method only calls super

Synopsis: "The method only calls it super", but the check actually looks for more than just that, for example:

  • The method and all its derivatives are empty
  • All implementations of this method are empty.
  • Method is empty
  • An empty method overrides an empty method

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

+8
source share

Using Structured Search, you will have to use two separate queries. One for finding methods with return type:

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

and second for methods returning a value:

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

An @Override annotation is not required in this case.

+1
source share

All Articles