Skip to content

Enforce preceding line break for opening braces of a case/default under switch in google_checks.xml #15324

Closed
@Zopsss

Description

I have read check documentation: https://checkstyle.sourceforge.io/checks/blocks/leftcurly.html
I have downloaded the latest checkstyle from: https://checkstyle.org/cmdline.html#Download_and_Run
I have executed the cli and showed it below, as cli describes the problem better than 1,000 words

Detected at: #14901 (comment)

As per the newly added Exception case in the section 4.1.2 Nonempty blocks: K & R style:

Exception: In places where these rules allow a single statement ending with a semicolon (;), a block of statements can appear, and the opening brace of this block is preceded by a line break. Blocks like these are typically introduced to limit the scope of local variables, for example inside switch statements.

If a block of code appears, then the opening brace ( { ) of that block should be preceded by a line break, for example:

case 42:
  {
    int x = foo();
    frob(x);
  }

Here a block of code appeared and its { is preceded by a line break but Checkstyle does not follow this updated rule, as of now we don't enforce a line break before the { for such code blocks, for example:

/** Testing. */
public class TestingLeftCurly {
  static void testing() {
    int xyz = 10;

    switch (xyz) {
      case 42:
        { // false positive warning
          xyz++;
          foo(xyz);
        }
        break;

      case 10: { // false negative, should give warning here
        xyz++;
        foo(xyz);
      }
      break;

      default:
        break;
    }
  }

  static void foo(int xyz) {
    // do nothing.
  }
}

Output:

$ java -jar .\checkstyle-10.17.0-all.jar -c .\google_checks.xml .\TestingLeftCurly.java
Starting audit...
[WARN] C:\checkstyle testing\TestingGoogleStyle\.\TestingLeftCurly.java:8:9: '{' at column 9 should be on the previous line. [LeftCurly]
Audit done.

As you can see, there's no violation for case 10: { while there should be one. And there is a false positive violation for case 42: \n{ while it is the correctly formatted code.


Describe what you expect in detail.

We should update LeftCurly module in google config to enforce new line before { of such coding blocks and also ensure to give violation if they are misplaces

Metadata

Assignees

Labels

approvedbugfalse positiveissues where check places violations on code, but should not

Type

No type

Projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions