liveBook · Manning

Range annotation

As explained in 100 Java Mistakes and How to Avoid Them

The Range annotation declares explicit lower and upper bounds for an annotated numeric value or parameter.

A Range annotation declares explicit lower and upper bounds for a numeric value or parameter. Used on an index parameter, it documents the valid interval and can help static analyzers flag invalid calls before an IndexOutOfBoundsException occurs. section 5.2

Annotating a nonnegative index

Use the JetBrains annotation package to express a nonnegative int parameter with an explicit range: @Range(from = 0, to = Integer.MAX_VALUE) int index This is equivalent to a @NonNegative annotation for an int parameter. A static analyzer may warn when a caller supplies a negative argument, but callers should still have their bounds checked immediately. section 5.2

Use range annotations to:

  • Document permitted numeric bounds directly on parameters. section 5.2
  • Aid static analysis during development rather than relying only on runtime failures. section 5.2
  • Keep immediate runtime bounds checks when accepting indexes from clients. section 5.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines explicit lower and upper bounds and analyzer support, but stops short of replacing immediate runtime checks.
Examples
Uses @Range(from = 0, to = Integer.MAX_VALUE) as the explicit nonnegative-int example.
What it assumes
Assumes familiarity with numeric parameters and indexes while distinguishing annotations from necessary runtime bounds checks.
What you can do after
Apply it via the JetBrains annotation package to document bounds and aid detection of invalid arguments.
How it connects
Connects range annotations with static analysis, IndexOutOfBoundsException, array indexes, and NonNegative annotations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.