A numeric literal other than a small common one is written inline instead of named
What it finds
A number such as 86400 or 0.15 in the middle of code says nothing about what it stands for, and when it changes, every copy has to be found. A named constant says what it is and keeps it in one place.
Not reported are numbers whose meaning is plain where they stand:
- the integers from 0 to 10, 16, 32, 64, 100, 128, 255, 256, 1000 and 1024, and 0.5, also negated and in their floating-point forms; - integers written in hexadecimal, octal or binary, which are bit patterns, and the right side of a shift or a bitwise operator; - numbers that initialize a final field or local variable, which names them; - numbers in annotations, case labels, enum constant arguments, array sizes and array initializers, and the capacity given to a new collection, buffer or builder; - arguments of assertions, as in assertEquals(3, list.size()) or hasSize(3); - numbers inside hashCode methods, where multipliers such as 31 are customary.
From the rule's source, magic_number.rs.
class Billing { static final int DAYS = 30; private static final double RATE = 0.15; double total(double amount, int days) { double fee = amount * 0.15;tx0 reports: the number 0.15 is written inline int weeks = days / 7; long seconds = days * 86400L;tx0 reports: the number 86400L is written inline int offset = -42;tx0 reports: the number -42 is written inline final int week = 14; int[] slots = new int[24]; int half = days / 2; int low = days & 0xFF; int shifted = days >> 12; java.util.List<String> names = new java.util.ArrayList<>(48); return fee + weeks + half + slots.length - 1 + low + shifted + offset + week + seconds + names.size(); } void check(java.util.List<String> names) { assertEquals(42, names.size()); } void assertEquals(int expected, int actual) {} @Override public int hashCode() { return 31 * DAYS + 17; }} Turn it on, off or suppress it
The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/java:inline-numeric-literal" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/java:inline-numeric-literal] reason="..."tx0 explain tx0/java:inline-numeric-literal shows the same in the terminal. Found a false positive? Report it.