Domanda

When using GCC to compile C or C++, you can mark functions with attribute((warn_unused_result)) which will cause the compiler to complain if you invoke a function that returns something and then don't assign it to anything.

I have some methods in a Java library I develop that have methods like this - calling them and then throwing away the result is always a bug. I would like API users to be able to identify such bugs via static analysis, such as with FindBugs or IntelliJ inspections.

I am wondering if there is a method annotation that is commonly used to mark methods or functions as "must use result". FindBugs has some special case bug-finders for the standard library, but a general way would be useful.

È stato utile?

Soluzione 3

There is totally a standard annotation for this, and it is @CheckReturnValue. FindBugs has it; see e.g. here.

Guava uses it internally -- e.g. in the configuration methods for Splitter -- from JSR 305.

Altri suggerimenti

Use

import javax.annotation.CheckReturnValue;
.
.
.
@CheckReturnValue

Some good examples of @CheckReturnValue are available on the Google error-prone project wiki. (If you like static analysis tools such as FindBugs, you should definitely check out error-prone; it works on the source/AST rather than the bytecode, which makes it complementary to tools such as FindBugs.)

If you're reading this in 2019 or later: annotate the method with @edu.umd.cs.findbugs.annotations.CheckReturnValue available from com.github.spotbugs:spotbugs-annotations. SpotBugs is an actively maintained successor to FindBugs.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top