There’s no point in forcing the overhead of a method call for a method that always returns the same constant value. Even worse, the fact that a
method call must be made will likely mislead developers who call the method thinking that something more is done. Declare a constant instead.
This rule raises an issue if on methods that contain only one statement: the return
of a constant value.
Noncompliant code example
int getBestNumber() {
return 12; // Noncompliant
}
Compliant solution
static final int BEST_NUMBER = 12;
Exceptions
The following types of method are ignored:
- methods that override a method.
- methods that are not final (not having the
final
, private
or static
modifier and not in a record or a
final class).
- methods with annotations, such as
@Override
or Spring’s @RequestMapping
.