11

I have had 'hidden' bugs due to Eclipse not reporting 'unused' variables because they were used in an assertion (precondition), for example:

public void method(final String text, ...other parameters) {
  assert StringUtils.isNotBlank(text);
  ...
  // The text variable is never used in the method.
  // If Eclipse had reported the variable as 'unused' I would have noticed that something is wrong with the code.
  ...
}

I would like to tell Eclipse to ignore assertions when checking for unused variables. I doubt anyone would pass a parameter to only run an assertion on it... Also let me know if FindBugs or another tool can do this.

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
  • 1
    FindBugs might be able to do this if you tell the compiler to leave out assertions in the byte code. Then FindBugs should see that the variable is unused. Unless of course the compiler removes the unused variable from the bytecode as well. (Which I'd expect.) Checkstyle and PMD do not have an "Ignore Assertions" flag afaik. – barfuin Feb 09 '14 at 12:52
  • You can use @NonNull annotation in your case to avoid assert http://help.eclipse.org/kepler/topic/org.eclipse.jdt.doc.user/tasks/task-using_null_annotations.htm?cp=1_3_9_0 – Konstantin Zaitsev Mar 25 '14 at 18:02
  • Following up on Thomas' answer. There is no switch to remove assertions from the bytecode. Here's how to do it: http://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html#usage-adv-removing – Barett Mar 26 '14 at 18:38
  • @Barett thanks, this may be a solution to find those issues from time to time. – Christophe Roussy Mar 27 '14 at 09:35
  • @KonstantinZaitsev Using the `@NonNull` annotation will not solve this issue, I am talking about any possible assertion, not just about `assert != null` (isNotBlank is doing more than checking for nullity) – Christophe Roussy Mar 27 '14 at 09:37
  • Not a solution, but a work-around: keep your assertion in your `method` method and, after that, call a `unsafeMethod` that accepts the same arguments and has no assertions. You'll get the warning there – espinchi May 02 '14 at 04:56

1 Answers1

1

Here is my own attempt at solving this with a 'brute' solution:

  • Write a script that makes a copy of your source code and removes all assertions from it
  • Inspect that assert less copy as you would inspect the original
  • Manually remove variables used only in asserts from the original source code

Note that there is a similar problem with JavaDoc linked variables... if a variable is mentioned in the JavaDoc it will be considered as used (by Eclipse and maybe other IDE).

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85