Use visually distinct identifiers that are unlikely to be misread during development and review of code. Depending on the fonts used, certain characters are visually similar or even identical and can be misinterpreted. Consider the following examples:examples in the following table.
Misleading characters
Intended Character | Could Be Mistaken for This Character, and Vice Versa |
---|---|
0 (zero) | O (capital o) |
1 (one) | I (capital i) |
2 (two) | Z (capital z) |
5 (five) | S (capital s) |
8 (eight) | B (capital b) |
n (lowercase N) | h (lowercase H) |
rn (lowercase R, lowercase N) | m (lowercase M) |
The Java Language Specification (JLS) mandates that program source code be written using the Unicode character encoding [Unicode 2013]. Some distinct Unicode characters share identical glyph representation when displayed in many common fonts. For example, the Greek and Coptic characters (Unicode Range 0370–03FF) are frequently indistinguishable from the Greek-character subset of the Mathematical Alphanumeric Symbols (Unicode Range 1D400–1D7FF).
...
Do not use multiple identifiers that vary by only one or more visually similar characters. Also, make the initial portions of long identifiers distinct to aid recognition.
According to the Java Language SpecificationJLS, §3.10.1, "Integer Literals" [JLS 20112013],
An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise, it is of type int. The suffix L is preferred because the letter l (ell) is often hard to distinguish from the digit 1 (one).
...
Integer literals with leading zeros, in actuality, assume denote octal values, not decimal values. According to §3.10.1, "Integer Literals" of the Java Language Specification JLS [JLS 20112013],
An octal numeral consists of an ASCII digit
0
followed by one or more of the ASCII digits0
through7
interspersed with underscores, and can represent a positive, zero, or negative integer.
...
Code Block | ||
---|---|---|
| ||
int stem; // Position near the front of the boat
/* ... */
int stern; // Position near the back of the boat
|
...
Code Block | ||
---|---|---|
| ||
int bow; // Position near the front of the boat
/* ... */
int stern; // Position near the back of the boat
|
...
When integer literals are intended to represent a decimal value, avoid padding with leading zeros. Use another technique instead, such as padding with whitespace, to preserve digit alignment.
...
Heuristic detection of identifiers with visually similar names is straightforward. Detection of identifiers that begin identically is more problematic because it hinges on what is considered an "initial portion." Confusing a lowercase letter l with a digit 1 when indicating that an integer denotation is a long
value can result in incorrect computations. Automated detection is trivial.
...
Puzzle 4, "It's Elementary" | |
[Seacord 20082009] | DCL02-C. Use visually distinct identifiers |
[Unicode 2013] |
...