JetBrains / java-annotations

Annotations for JVM-based languages.
Apache License 2.0
404 stars 47 forks source link

Add @Range annotation to set a boundary for number parameters or array parameters #7

Closed burdoto closed 5 years ago

burdoto commented 5 years ago

The Annotation is documented as intended.

This annotation defines the allowed range of a number parameter.
The method may throw an {@link IllegalArgumentException} if the parameter is not within its bounds.
If the annotation is used on a {@code VarArgs} parameter, it describes the minimum and maximum amount of arguments.

Of course, this PR is missing all logic towards this annotation, this PR mostly serves as an idea that I want to share to the JetBrains team.

In example, IntelliJ could, if wanted by the user, add range-checking snippets before compiling; the same goes for things like the @Nullable annotation.

amaembo commented 5 years ago

Hello and thank you for contribution. Unfortunately I'm not sure that we can accept in in current shape.

First, we already have an experimental Range annotation defined in IntelliJ IDEA. It's already respected in our static analysis when this annotation is specified for method return value or field. We use it to annotate standard library externally (e.g. LocalDateTime#getHour is annotated as @Range(from = 0, to = 23)). If there's a demand for such annotation, we may consider publishing it. However note that we are using from and to. Seems these parameter names are more popular than min and max, at least they are used in Checker framework and Android SDK. Also I'm in doubt whether default value for min should be specified as 0. If you want to declare parameter as non-negative, it would be @Range(max = Integer.MAX_VALUE) which looks completely strange.

Finally I don't like the idea of using the same annotation to limit the number of vararg elements. This violates single responsibility principle. Also this is simply confusing: @Range(min = 0, max = 10) int... args could be considered as arbitrary number of arguments, each from 0 to 10, but according to your description it's 0 to 10 arguments with unrestricted values. And I don't see any practical use cases when number of varargs should be limited. Which problem requires limited number of varargs? And if it's actually necessary, you may alternatively consider adding a fixed number of overloads. This way it will be controlled on compiler level, rather than via static analysis or annotation processor.

So to track publishing of Range annotation I created issue #8. This pull request is closed.