Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Misleading indentation

ID: java/misleading-indentationKind: problemSecurity severity: Severity: warningPrecision: very-highTags:   - quality   - maintainability   - readability   - correctness   - logicQuery suites:   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

A control structure (anif statement or a loop) has a body that is either a block of statements surrounded by curly braces or a single statement.

If you omit braces, it is particularly important to ensure that the indentation of the code matches the control flow of the code.

Recommendation

It is usually considered good practice to include braces for all control structures in Java. This is because it makes it easier to maintain the code later. For example, it’s easy to see at a glance which part of the code is in the scope of anif statement, and adding more statements to the body of theif statement is less error-prone.

You should also ensure that the indentation of the code is consistent with the actual flow of control, so that it does not confuse programmers.

Example

In the example below, the original version ofCart is missing braces. This means that the code triggers aNullPointerException at runtime ifi isnull.

classCart{Map<Integer,Integer>items=...publicvoidaddItem(Itemi){// No braces and misleading indentation.if(i!=null)log("Adding item: "+i);// Indentation suggests that the following statements// are in the body of the 'if'.IntegercurQuantity=items.get(i.getID());if(curQuantity==null)curQuantity=0;items.put(i.getID(),curQuantity+1);}}

The corrected version ofCart does include braces, so that the code executes as the indentation suggests.

classCart{Map<Integer,Integer>items=...publicvoidaddItem(Itemi){// Braces included.if(i!=null){log("Adding item: "+i);IntegercurQuantity=items.get(i.getID());if(curQuantity==null)curQuantity=0;items.put(i.getID(),curQuantity+1);}}}

In the following example the indentation may or may not be misleading depending on your tab width settings. As such, mixing tabs and spaces in this way is not recommended, since what looks fine in one context can be very misleading in another.

// Tab width 8if(b)// Indentation: 1 tabf();// Indentation: 2 tabsg();// Indentation: 8 spaces// Tab width 4if(b)// Indentation: 1 tabf();// Indentation: 2 tabsg();// Indentation: 8 spaces

If you mix tabs and spaces in this way, then you might get seemingly false positives, since your tab width settings cannot be taken into account.

References


[8]ページ先頭

©2009-2025 Movatter.jp