...
This misinterpretation may result in programming errors and is more likely to occur while declaring multiple constants and trying to enhance the formatting with zero padding.
Noncompliant Code Example
This noncompliant code example has two variables, stem
and stern
, within the same scope that can be easily confused and accidentally interchanged:
Code Block | ||
---|---|---|
| ||
int stem; // Position near the front of the boat /* ... */ int stern; // Position near the back of the boat |
Compliant Solution
This compliant solution eliminates the confusion by assigning visually distinct identifiers to the variables:
Code Block | ||
---|---|---|
| ||
int bow; // Position near the front of the boat /* ... */ int stern; // Position near the back of the boat |
Noncompliant Code Example
This noncompliant example prints the result of adding an int
and a long
value even though it appears that two integers 11111
are being added:
Code Block | ||
---|---|---|
| ||
public class Visual { public static void main(String[] args) { System.out.println(11111 + 1111l); } } |
Compliant Solution
This compliant solution uses an uppercase L
(long
) instead of lowercase l
to disambiguate the visual appearance of the second integer. Its behavior is the same as that of the noncompliant code example, but the programmer's intent is clear:
Code Block | ||
---|---|---|
| ||
public class Visual { public static void main(String[] args) { System.out.println(11111 + 1111L); } } |
Noncompliant Code Example
This noncompliant example mixes decimal values and octal values while storing them in an array:
...
It appears that the third element in array
is intended to hold the decimal value 42. However, the decimal value 34 (corresponding to the octal value 42) gets assigned.
Compliant Solution
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.
Code Block | ||
---|---|---|
| ||
int[] array = new int[3]; void exampleFunction() { array[0] = 2719; array[1] = 4435; array[2] = 42; // ... } |
Applicability
Failing to use visually distinct identifiers could result in the use of the wrong identifier and lead to unexpected program behavior.
...
Detection of integer literals that have a leading zero is trivial. However, determining whether the programmer intended to use an octal literal or a decimal literal is infeasible. Accordingly, sound automated detection is also infeasible. Heuristic checks may be useful.
Bibliography
Puzzle 4, "It's Elementary" | |
[JLS 2011] | |
[Seacord 2008] | DCL02-C. Use visually distinct identifiers |
[Unicode 2013] |
...