CodeNarc - CodeNarc - Formatting Rules

##### General

- Home
- Downloads
- Javadocs
- Mailing Lists
- Bug Tracker
- SourceForge Project
- GitHub Project

##### Running

- Ant Task Usage
- Command-Line
- Run as a Test
- Other Tools/Frameworks

##### Using

- Creating a RuleSet
- Creating a Rule
- Configuring Rules
- Starter RuleSet (All)

##### Report Types

- HTML Report
- XML Report
- Text and IDE Reports

##### Sample Reports

- Sample HTML Report
- Sample XML Report

##### Rules

- Rule Index
- Basic Rules
- Braces Rules
- Concurrency Rules
- Convention Rules
- Design Rules
- DRY Rules
- Enhanced Rules
- Exceptions Rules
- Formatting Rules
- Generic Rules
- Grails Rules
- Groovyism Rules
- Imports Rules
- JDBC Rules
- JUnit Rules
- Logging Rules
- Naming Rules
- Size/Complexity Rules
- Security Rules
- Serialization Rules
- Unnecessary Rules
- Unused Rules

##### Developing

- Developer Guide

##### Project Documentation

- Project Information
- Project Reports

## Formatting Rules ("rulesets/formatting.xml")

### BlankLineBeforePackage Rule

Since CodeNarc 0.21

Makes sure there are no blank lines before the package declaration of a source code file.

### BracesForClass Rule

Since CodeNarc 0.15

Checks the location of the opening brace ({) for classes. By default, requires them on the same line, but the `sameLine` property can be set to false to override this.

NOTE: This rule ignores annotation types, e.g. `@interface MyAnnotation` .

### BracesForForLoop Rule

Since CodeNarc 0.15

Checks the location of the opening brace ({) for for loops. By default, requires them on the same line, but the `sameLine` property can be set to false to override this.

### BracesForIfElse Rule

Since CodeNarc 0.15

Checks the location of the opening brace ({) for if statements. By default, requires them on the same line, but the `sameLine` property can be set to false to override this.

### BracesForMethod Rule

Since CodeNarc 0.15

Checks the location of the opening brace ({) for constructors and methods. By default, requires them on the same line, but the `sameLine` property can be set to false to override this.

### BracesForTryCatchFinally Rule

Since CodeNarc 0.15

Checks the location of the opening brace ({) for try statements. By default, requires them on the line, but the `sameLine` property can be set to false to override this.

### ClassJavadoc Rule

Since CodeNarc 0.15

Makes sure each class and interface definition is preceded by javadoc. Enum definitions are not checked, due to strange behavior in the Groovy AST. By default, only the main class in a file is checked for Javadoc. The main class is defined as the class that has the same name as the source file, for instance MyClass is the main class in MyClass.groovy but the class MyOtherClass defined in the same source file is not the main class. To check all the classes in the file set the rule property `applyToNonMainClasses` to true.

### ClosureStatementOnOpeningLineOfMultipleLineClosure Rule

Since CodeNarc 0.20

Checks for closure logic on first line (after `->`) for a multi-line closure. That breaks the symmetry of indentation (if the subsequent statements are indented normally), and that first statement can be easily missed when reading the code.

Example of violations:

        def closure = { name -> println name
            addToCounts()
            println “done” }

### ConsecutiveBlankLines Rule

Since CodeNarc 0.21

Makes sure there are no consecutive lines that are either blank or whitespace only. This reduces the need to scroll further than necessary when reading code, and increases the likelihood that a logical block of code will fit on one screen for easier comprehension.

Example of violation:

        def name

        def value

        def id

### FileEndsWithoutNewline Rule

Since CodeNarc 0.21

Makes sure each source file ends with a newline character.

### LineLength Rule

Since CodeNarc 0.15

Checks the maximum length for each line of source code. It checks for number of characters, so lines that include tabs may appear longer than the allowed number when viewing the file. The maximum line length can be configured by setting the length property, which defaults to 120.

NOTE: This rule does not support the @SuppressAnnotations annotation or the classname-based rule properties (applyToClassNames, doNotApplyToClassNames) to enable/disable the rule. If you want to specify or restrict where this rule is applied, you must use the file-based rule properties: applyToFileNames, doNotApplyToFileNames, applyToFilesMatching and doNotApplyToFilesMatching.

### MissingBlankLineAfterImports Rule

Since CodeNarc 0.21

Makes sure there is a blank line after the imports of a source code file.

Example of violation:

        import org.apache.commons.lang.StringUtils
        class MyClass { }                       // violation

### MissingBlankLineAfterPackage Rule

Since CodeNarc 0.21

Makes sure there is a blank line after the package statement of a source code file.

Example of violation:

      package org.codenarc
      import java.util.Date                     // violation

      class MyClass {
          void go() { /* ... */ }
      }

### SpaceAfterCatch Rule

Since CodeNarc 0.18

Check that there is exactly one space (blank) after the `catch` keyword and before the opening parenthesis.

Examples of violations:

        try { } catch(Exception e) { }          // violation
        try { } catch  (Exception e) { }        // violation

### SpaceAfterComma Rule

Since CodeNarc 0.18

Checks that there is at least one space or whitespace following each comma. That includes checks for method and closure declaration parameter lists, method call parameter lists, Map literals and List literals.

Known limitations:

- May not catch actual violations if the source line contains unicode character literals, e.g. `'\u00A0'`

Examples of violations:

        def value = calculate(1,399, 'abc')         // violation on parameter 399

        def method1(int a,String b) { }             // violation on parameter b

        def closure1 = { int a,String b -> }        // violation on parameter b

        def list1 = [a,b, c]                        // violation on list element b

        def map1 = [a:1,b:2, c:3]                   // violation on map element b:2

### SpaceAfterClosingBrace Rule

Since CodeNarc 0.18

Check that there is at least one space (blank) or whitespace after each closing brace ("{") for method/class/interface declarations, closure expressions and block statements.

A closure expression followed by a dot operator (.), a comma, a closing parenthesis, the spread-dot operator (*.), a semicolon or the null-safe operator (?.) does not cause a violation.

Property | Description | Default Value
checkClosureMapEntryValue | If `false`, then do not check for whitespace after closing braces for closure expressions that are literal Map values, e.g. `[abc:doStuff()]`. | `true`

Known limitations:

- May not catch actual violations if the source line contains unicode character literals, e.g. `'\u00A0'`

Examples of violations and exceptions:

        if (ready) { return 9 }else { }             // violation
        try { doStuff() }finally { }                // violation

        def matching = list.find { it.isReady() }.filter()  // no violation for dot operator
        assert list.every { it.isReady() }, "Error"         // no violation for comma
        def m = [a:123, b:{ println 7 },c:99]               // no violation for comma
        processItems(list.select { it.isReady() })          // no violation for closing parenthesis
        def names = records.findAll { it.age > 1 }*.name    // no violation for spread operator
        list?.collect { it?.type }?.join(',')               // no violation for null-safe operator

### SpaceAfterFor Rule

Since CodeNarc 0.18

Check that there is exactly one space (blank) after the `for` keyword and before the opening parenthesis.

Examples of violations:

        for(name in names) { }                  // violation
        for  (int i=0; i < 10; i++) { }         // violation

### SpaceAfterIf Rule

Since CodeNarc 0.18

Check that there is exactly one space (blank) after the `if` keyword and before the opening parenthesis.

Examples of violations:

        if(true) { }                            // violation
        if  (true) { }                          // violation

### SpaceAfterOpeningBrace Rule

Since CodeNarc 0.18

Check that there is at least one space (blank) or whitespace after each opening brace ("{") for method/class/interface declarations, closure expressions and block statements.

Property | Description | Default Value
checkClosureMapEntryValue | If `false`, then do not check for whitespace after opening braces for closure expressions that are literal Map values, e.g. `[abc:doStuff()]`. | `true`
ignoreEmptyBlock | If `true`, then allow for `[]` in code | `false`

Examples of violations:

        class MyClass{int count }                   // violation

        interface MyInterface {static final OK = 1 }// violation

        enum MyEnum {OK, BAD }                      // violation

        def myMethod() {int count }                 // violation

        if (ready) {println 9 }                     // violation

        if (ready) {
        } else {println 99}                         // violation

        for (int i=0; i<10; i++) {println i }       // violation

        for (String name in names) {println name }  // violation

        for (String name: names) {println name }    // violation

        while (ready) {println time }               // violation

        try {doStuff()                              // violation
        } catch(Exception e) {x=77 }                // violation
        } finally {println 'error' }                // violation

        list.each {name -> }                        // violation

        shouldFail(Exception) {doStuff() }          // violation

### SpaceAfterSemicolon Rule

Since CodeNarc 0.18

Check that there is at least one space (blank) or whitespace following a semicolon that separates:

- multiple statements on a single line
- the clauses within a classic for loop, e.g. for (i=0;i<10;i++)

Examples of violations:

        def myMethod() {
            println 1;println 2                         // violation
            def closure = { x -> doStuff();x = 23; }    // violation

            for (int i=0;i < 10;i++) {                  // violations (2)
                for (int j=0; j < 10;j++) { }           // violation
            }
        }

### SpaceAfterSwitch Rule

Since CodeNarc 0.18

Check that there is exactly one space (blank) after the `switch` keyword and before the opening parenthesis.

Examples of violations:

        switch(x) {                                 // violation
            case 1: println 'one'
        }
        switch  (x) {                               // violation
            case 1: println 'one'
        }

### SpaceAfterWhile Rule

Since CodeNarc 0.18

Check that there is exactly one space (blank) after the `while` keyword and before the opening parenthesis.

Examples of violations:

        while(true) { }             // violation
        while  (true) { }           // violation

### SpaceAroundClosureArrow Rule

Since CodeNarc 0.19

Checks that there is at least one space (blank) or whitespace around each closure arrow (->) symbol.

Known limitations:

- Does not catch violations if the closure arrow (->) is on a separate line from the start of the closure.

Example of violations:

        def closure1 = {->}                             // violation
        def closure2 = { ->}                            // violation
        def closure3 = {-> }                            // violation
        def closure4 = { count-> println 123 }          // violation
        def closure5 = { count, name ->println 123 }    // violation

### SpaceAroundMapEntryColon Rule

Since CodeNarc 0.20

Check for proper formatting of whitespace around colons for literal Map entries. By default, no whitespace is allowed either before or after the Map entry colon, but you can change that through the configuration properties below.

Property | Description | Default Value
characterBeforeColonRegex | The regular expression that must match the character before the colon (:) for a literal Map entry. For example, `/\S/` matches any non-whitespace character and `/\s/` matches any whitespace character (thus requiring a space or whitespace). | `/\S/` (i.e., no space allowed before the colon)
characterAfterColonRegex | The regular expression that must match the character after the colon (:) for a literal Map entry. For example, `/\S/` matches any non-whitespace character and `/\s/` matches any whitespace character (thus requiring a space or whitespace). | `/\S/` (i.e., no space allowed before the colon)

Example of violations:

        Map m1 = [myKey : 12345]            // violation (both before and after the colon)
        println [a :[1:11, 2:22],           // violation on a (before colon)
                    b:[(Integer): 33]]      // violation on Integer (after colon)

### SpaceAroundOperator Rule

Since CodeNarc 0.18

Check that there is at least one space (blank) or whitespace around each binary operator, including: +, -, *, /, >>, <<, &&, ||, &, |, ?:, =, "as".

Do not check dot ('.') operator. Do not check unary operators (!, +, -, ++, --, ?.). Do not check array ('[') operator.

Known limitations:

- Does not catch violations of missing space around equals operator (=) within a declaration expression, e.g. `def x=23`
- Does not catch violations of certain ternary expressions and standalone elvis operator (?:) expressions

Examples of violations:

        def myMethod() {
            3+ 5-x*23/ 100              // violation
            list \<\<123                // violation
            other\>\> writer            // violation
            x=99                        // violation
            x&& y                       // violation
            x ||y                       // violation
            x &y                        // violation
            x| y                        // violation
            [1,2]as String              // violation
        }

### SpaceBeforeClosingBrace Rule

Since CodeNarc 0.18

Check that there is at least one space (blank) or whitespace before each closing brace ("}") for method/class/interface declarations, closure expressions and block statements.

Property | Description | Default Value
checkClosureMapEntryValue | If `false`, then do not check for whitespace before closing braces for closure expressions that are literal Map values, e.g. `[abc:doStuff()]`. | `true`
ignoreEmptyBlock | If `true`, then allow for `[]` in code | `false`

Known limitations:

- May not catch actual violations if the source line contains unicode character literals, e.g. `'\u00A0'`

Examples of violations:

        class MyClass { int count}                  // violation

        interface MyInterface { void doStuff()}     // violation

        enum MyEnum { OK, BAD}                      // violation

        def myMethod() { return 9}                  // violation

        if (ready) { doStuff()}                     // violation

        if (ready) {
        } else { return 9}                          // violation

        for (int i=0; i<10; i++) { println i}       // violation

        for (String name in names) { println name}  // violation

        for (String name: names) { println name}    // violation

        while (ready) { doStuff()}                  // violation

        try { doStuff()}                            // violation
        catch(Exception e) { logError(e)}           // violation
        finally { cleanUp()}                        // violation

        list.each { name -> println name}           // violation

        shouldFail(Exception) { doStuff()}          // violation

### SpaceBeforeOpeningBrace Rule

Since CodeNarc 0.18

Check that there is at least one space (blank) or whitespace before each opening brace ("{") for method/class/interface declarations, closure expressions and block statements.

Property | Description | Default Value
checkClosureMapEntryValue | If `false`, then do not check for whitespace before opening braces for closure expressions that are literal Map values, e.g. `[abc:doStuff()]`. | `true`

Known limitations:

- May not catch actual violations if the source line contains unicode character literals, e.g. `'\u00A0'`

Examples of violations:

        class MyClass{ }                            // violation
        class MyOtherClass extends AbstractClass{ } // violation

        interface MyInterface{ }                    // violation

        enum MyEnum{ OK, BAD }                      // violation

        def myMethod(){ }                           // violation

        if (ready){ }                               // violation

        if (ready) {
        } else{}                                    // violation

        for (int i=0; i<10; i++){ }                 // violation

        for (String name in names){ }               // violation

        for (String name: names){ }                 // violation

        while (ready){ }                            // violation

        try{
        } finally { }                               // violation

        try {
        } catch(Exception e){ }                     // violation

        try {
        } finally{ }                                // violation

        list.each{ name -> }                        // violation

        shouldFail(Exception){ doStuff() }          // violation

### TrailingWhitespace Rule

Since CodeNarc 0.21

Checks that no lines of source code end with whitespace characters.