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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With