Skip to content

All rules

Block tag punctuation

Description of certain block tags, if present, should end with a period, question mark or exclamation mark.

Before

/**
 * @param num
 * @return the new size of the group
 */
abstract int add(int num);
/**
 * @param num
 * @return the new size of the group
 */
abstract def add(int num)
/**
 * @param num
 * @return the new size of the group
 */
abstract fun add(int num): Int
/**
 * @param num
 * @return the new size of the group
 */
virtual int add(int num) = 0;

After

/**
* @param num
* @return the new size of the group.
*/
abstract int add(int num);
/**
* @param num
* @return the new size of the group.
*/
abstract def add(int num)
/**
* @param num
* @return the new size of the group.
*/
abstract fun add(int num): Int
/**
* @param num
* @return the new size of the group.
*/
virtual int add(int num) = 0;
Configuration
Setting Default value
BlockTagPunctuation#tags @param, @return
BlockTagPunctuation#tags @param, @return
rulebook_punctuate_block_tags @constructor, @receiver, @property, @param, @return
--punctuate-block-tags @param, @return

TODO comment

TODO comment keywords should be uppercase and followed by exactly one space.

Before

// todo add tests
//
// FIXME: memory leak
// todo add tests
//
// FIXME: memory leak
// todo add tests
//
// FIXME: memory leak
// todo add tests
//
// FIXME: memory leak
# todo add tests
#
# FIXME: memory leak
// todo add tests
//
// FIXME: memory leak
// todo add tests
//
// FIXME: memory leak

After

// TODO add tests
//
// FIXME memory leak
// TODO add tests
//
// FIXME memory leak
// TODO add tests
//
// FIXME memory leak
// TODO add tests
//
// FIXME memory leak
# TODO add tests
#
# FIXME memory leak
// TODO add tests
//
// FIXME memory leak
// TODO add tests
//
// FIXME memory leak

Trailing comma in call

Put a trailing comma in a multiline call site, omit when it is a single line.

Before

var items =
    [
        'milks',
        'eggs'
    ] as Set

println(items,)
val items =
    setOf(
        "milks",
        "eggs"
    )

println(items,)
items = \
    set(
        'milks',
        'eggs'
    )

print(items,)
const items =
    new Set([
        'milks',
        'eggs'
    ]);

console.log(items,);
const items: Set<string> =
    new Set([
        'milks',
        'eggs'
    ]);

console.log(items,);

After

var items =
    [
        'milks',
        'eggs',
    ] as Set

println(items)
val items =
    setOf(
        "milks",
        "eggs",
    )

println(items)
items = \
    set(
        'milks',
        'eggs',
    )

print(items)
const items =
    new Set([
        'milks',
        'eggs',
    ]);

console.log(items);
const items: Set<string> =
    new Set([
        'milks',
        'eggs',
    ]);

console.log(items);

Trailing comma in collection

Put a trailing comma in a multiline collection site, omit when it is a single line. In Java and Groovy, this rule applies to array initializers. In Python, this rule applies to tuples.

Before

int[][] ticTacToe = {
    {0, 0, 0,},
    {0, 0, 0,},
    {0, 0, 0,}
};
var ticTacToe = [
    [0, 0, 0,],
    [0, 0, 0,],
    [0, 0, 0,]
]
tic_tac_toe = (
    (0, 0, 0,),
    (0, 0, 0,),
    (0, 0, 0,)
)
const ticTacToe = [
    [0, 0, 0,],
    [0, 0, 0,],
    [0, 0, 0,]
];
const ticTacToe: number[][] = [
    [0, 0, 0,],
    [0, 0, 0,],
    [0, 0, 0,]
];

After

int[][] ticTacToe = {
    {0, 0, 0},
    {0, 0, 0},
    {0, 0, 0},
};
var ticTacToe = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0],
]
tic_tac_toe = (
    (0, 0, 0),
    (0, 0, 0),
    (0, 0, 0),
)
const ticTacToe = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0],
];
const ticTacToe: number[][] = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0],
];

Trailing comma in declaration

Put a trailing comma in a multiline declaration site, omit when it is a single line.

Before

fun updateInventory(item: String,) {}

fun createInventory(
    item: String,
    quantity: Int
) {}
def update_inventory(item,):
    pass


def create_inventory(
    item,
    quantity
):
    pass
function updateInventory(item,) {}

function createInventory(
    item,
    quantity
) {}
function updateInventory(item: string,): void {}

function createInventory(
    item: string,
    quantity: number
): void {}

After

fun updateInventory(item: String) {}

fun createInventory(
    item: String,
    quantity: Int,
) {}
def update_inventory(item):
    pass


def create_inventory(
    item,
    quantity,
):
    pass
function updateInventory(item) {}

function createInventory(
    item,
    quantity,
) {}
function updateInventory(item: string): void {}

function createInventory(
    item: string,
    quantity: number,
): void {}

Unused import

Remove unused import statements.

Before

import com.example.fruit.Apple;
import com.example.fruit.Banana;

Apple apple = new Apple();
import com.example.fruit.Apple
import com.example.fruit.Banana

var apple = new Apple()
import com.example.fruit.Apple
import com.example.fruit.Banana

val apple = Apple()
from fruit import Apple, Banana

apple = Apple()
import { Apple, Banana } from 'fruit';

const apple = new Apple();
import { Apple, Banana } from 'fruit';

const apple: Apple = new Apple();

After

import com.example.fruit.Apple;

Apple apple = new Apple();
import com.example.fruit.Apple

var apple = new Apple()
import com.example.fruit.Apple

val apple = Apple()
from fruit import Apple

apple = Apple()
import { Apple } from 'fruit';

const apple = new Apple();
import { Apple } from 'fruit';

const apple: Apple = new Apple();

Wildcard import

Import directives must be single-type instead of wildcard imports.

Before

import com.example.fruit.*;

List<Fruit> fruits = Arrays.asList(new Apple(), new Banana());
import com.example.fruit.*

var fruits = [new Apple(), new Banana()]
import com.example.fruit.*

val fruits = listOf(Apple(), Banana())
from fruit import *

fruits = [Apple(), Banana()]
import * as fruit from 'fruit';

const fruits = [new fruit.Apple(), new fruit.Banana()];
import * as fruit from 'fruit';

const fruits: Fruit[] = [new fruit.Apple(), new fruit.Banana()];

After

import com.example.fruit.Apple;
import com.example.fruit.Banana;

List<Fruit> fruits = Arrays.asList(new Apple(), new Banana());
import com.example.fruit.Apple
import com.example.fruit.Banana

var fruits = [new Apple(), new Banana()]
import com.example.fruit.Apple
import com.example.fruit.Banana

val fruits = listOf(Apple(), Banana())
from fruit import Apple, Banana

fruits = [Apple(), Banana()]
import { Apple, Banana } from 'fruit';

const fruits = [new Apple(), new Banana()];
import { Apple, Banana, Fruit } from 'fruit';

const fruits: Fruit[] = [new Apple(), new Banana()];

Clipping

Block comment clip

Short block comments should be written in a single line.

Before

/**
 * The quick brown fox jumps over the lazy dog.
 */
/**
 * The quick brown fox jumps over the lazy dog.
 */
/**
 * The quick brown fox jumps over the lazy dog.
 */
"""
The quick brown fox jumps over the lazy dog.
"""
/**
 * The quick brown fox jumps over the lazy dog.
 */
/**
 * The quick brown fox jumps over the lazy dog.
 */

After

/** The quick brown fox jumps over the lazy dog. */
/** The quick brown fox jumps over the lazy dog. */
/** The quick brown fox jumps over the lazy dog. */
"""The quick brown fox jumps over the lazy dog."""
/** The quick brown fox jumps over the lazy dog. */
/** The quick brown fox jumps over the lazy dog. */

Braces clip

Empty code blocks should be joined with the preceding code.

Before

void main() {
}
def main() {
}
fun main() {
}
void main() {
}
foo = {
}
function main() {
}
function main(): void {
}

After

void main() {}
def main() {}
fun main() {}
void main() {}
foo = {}
function main() {}
function main(): void {}

Brackets clip

Empty collection initializers should be joined with the preceding code.

Before

var numbers = [
]
std::vector<int> numbers = {
};
numbers = [
]
const numbers = [
];
const numbers: number[] = [
];

After

var numbers = []
std::vector<int> numbers = {};
numbers = []
const numbers = [];
const numbers: number[] = [];

Parentheses clip

Empty method declarations and calls should be joined with the preceding code.

Before

void recurse(
) {
    recurse(
    );
}
def recurse(
) {
    recurse(
    )
}
fun recurse(
) {
    recurse(
    )
}
void recurse(
) {
    recurse(
    );
}
def recurse(
):
    recurse(
    )
function recurse(
) {
    recurse(
    );
}
function recurse(
): void {
    recurse(
    );
}

After

void recurse() {
    recurse();
}
def recurse() {
    recurse()
}
fun recurse() {
    recurse()
}
void recurse() {
    recurse();
}
def recurse():
    recurse()
function recurse() {
    recurse();
}
function recurse(): void {
    recurse();
}

Tags clip

Empty generic types should be joined with the preceding code.

Before

List<Float> points =
    new ArrayList<
        >();
var points =
    new ArrayList<
        >()
template<
> int points() {
    return 0;
}

After

List<Float> points =
    new ArrayList<>();
var points =
    new ArrayList<>()
template<> int points() {
    return 0;
}

Declaring

Deprecated type

Prefer to use built-in types provided by the language.

Before

import java.util.ArrayList

val names = arrayListOf<String>()
val people = java.util.ArrayList<Person>()
from typing import Optional

def get_name(person) -> Optional[str]:
    return person['name']
type Nullable<T> = T | null;

function getName(person: any): Nullable<string> {
    return person.name;
}

After

val names = arrayListOf<String>()
val people = ArrayList<Person>()
def get_name(person) -> str | None:
    return person['name']
function getName(person: any): string | null {
    return person.name;
}

Double quotes in block comment

Use double quotes in Python docstrings.

Before

'''
The quick brown fox jumps over the lazy dog.
'''

After

"""
The quick brown fox jumps over the lazy dog.
"""

Internal error

Use Exception as superclass of custom exceptions. Most applications should not extend Error or Throwable.

Before

class PurchaseException extends Error {}
class PurchaseException extends Error {}
class PurchaseException : Error()
class PurchaseException(BaseException):
    pass

After

class PurchaseException extends Exception {}
class PurchaseException extends Exception {}
class PurchaseException : Exception()
class PurchaseException(Exception):
    pass

Lowercase d

Double floating point literals should be suffixed with lowercase d, which is more readable than D.

Before

double quarter = 0.25D;
var quarter = 0.25D

After

double quarter = 0.25d;
var quarter = 0.25d

Lowercase f

Floating point literals should be suffixed with lowercase f.

Before

float half = 0.5F;
var quarter = 0.25F
val half = 0.5F
float half = 0.5F;

After

float half = 0.5f;
var quarter = 0.25f
val half = 0.5f
float half = 0.5f;

Lowercase Hexadecimal

All letters in hexadecimal literals should be lowercase.

Before

int color = 0xFF00FF;
var color = 0xFF00FF
val color = 0xFF00FF
int color = 0xFF00FF;
color = 0xFF00FF
const color = 0xFF00FF;
const color: number = 0xFF00FF;

After

int color = 0xff00ff;
var color = 0xff00ff
val color = 0xff00ff
int color = 0xff00ff;
color = 0xff00ff
const color = 0xff00ff;
const color: number = 0xff00ff;

Lowercase i

Integer literals should be suffixed with lowercase i.

Before

var ten = 10I

After

var ten = 10i

Missing inline in contract

Kotlin contract functions that carry a runnable parameter should have inline modifier. Without the modifier, user cannot assign a global variable within the code block.

Before

fun action(block: () -> Unit) {
    contract { callsInPlace(block, EXACTLY_ONCE) }
    block()
}

After

inline fun action(block: () -> Unit) {
    contract { callsInPlace(block, EXACTLY_ONCE) }
    block()
}

Missing private constructor

Utility classes should have a final modifier and a private constructor to prevent instantiation.

Before

class Lists {
    static List<String> of(String... elements) {
        return Arrays.asList(elements);
    }
}
class Lists {
    static List<String> of(String... elements) {
        return Arrays.asList(elements)
    }
}

After

final class Lists {
    private Lists() {}

    static List<String> of(String... elements) {
        return Arrays.asList(elements);
    }
}
final class Lists {
    private Lists() {}

    static List<String> of(String... elements) {
        return Arrays.asList(elements)
    }
}

Redundant qualifier

Strip fully qualified names when they are already imported.

Before

import java.io.FileInputStream;

void read(java.io.FileInputStream stream) {}
import java.io.FileInputStream

def read(java.io.FileInputStream stream) {}

After

import java.io.FileInputStream;

void read(FileInputStream stream) {}
import java.io.FileInputStream

def read(FileInputStream stream) {}

Single quotes in literal

Wrap string in single quotes, unless there is a template or a single quote.

Before

var name = "John Doe"

println('G\'day, ' + name)
name = "John Doe"

print('G\'day, ' + name)
const name = "John Doe";

console.log('G\'day, ' + name);
const name: string = "John Doe";

console.log('G\'day, ' + name);

After

var name = 'John Doe'

println("G'day, " + name)
name = 'John Doe'

print("G'day, " + name)
const name = 'John Doe';

console.log(`G'day, ${name}`);
const name: string = 'John Doe';

console.log(`G'day, ${name}`);

Unnecessary abstract

Abstract classes need at least one abstract function.

Before

abstract class Vehicle {
    void start() {}
}
abstract class Vehicle {
    def start() {}
}
abstract class Vehicle {
    fun start() {}
}
from abc import ABC

class Vehicle(ABC):
    def start(self):
        pass
abstract class Vehicle {
    start() {}
}

After

class Vehicle {
    void start() {}
}
class Vehicle {
    def start() {}
}
class Vehicle {
    fun start() {}
}
class Vehicle:
    def start(self):
        pass
class Vehicle {
    start() {}
}

Unnecessary parentheses in lambda

Single parameter lambdas should not have parentheses.

Before

files.forEach((file) -> System.out.println(file));
files.forEach((file) -> System.out.println(file))
files.forEach((file) => console.log(file));
files.forEach((file: string) => console.log(file));

After

files.forEach(file -> System.out.println(file));
files.forEach(file -> System.out.println(file))
files.forEach(file => console.log(file));
files.forEach((file: string) => console.log(file));

Tip

Parentheses on lambda parameters is a syntax error in:

  • Kotlin if parameter is single
  • Groovy closures, not lambdas

Uppercase L

Long integer literals should be suffixed with uppercase L.

Before

long tenMillion = 10_000_000l;
var tenMillion = 10_000_000l
long ten_million = 10'000'000l;

After

long tenMillion = 10_000_000L;
var tenMillion = 10_000_000L
long ten_million = 10'000'000L;

Expressing

Complicated boolean equality

Simplify boolean expressions when applicable.

Before

boolean valid = isReady() == true && isRunning() == false;
var valid = isReady() == true && isRunning() == false
val valid = isReady() == true && isRunning() == false
valid = is_ready() == True and is_running() == False
const valid: boolean = isReady() === true && isRunning() === false;

After

boolean valid = isReady() && !isRunning();
var valid = isReady() && !isRunning()
val valid = isReady() && !isRunning()
valid = is_ready() and not is_running()
const valid: boolean = isReady() && !isRunning();

Complicated size equality

Use isEmpty() or isNotEmpty() instead of comparing collection size with zero. In languages with truthy values, use the collection itself in a boolean context.

Before

if (files.size() > 0) {
    collect(files);
}
if (files.size() > 0) {
    collect(files)
}
if (files.size > 0) {
    collect(files)
}
if len(files) > 0:
    collect(files)
if (files.length > 0) {
    collect(files);
}
if (files.length > 0) {
    collect(files);
}

After

if (!files.isEmpty()) {
    collect(files);
}
if (!files.isEmpty()) {
    collect(files)
}
if (files.isNotEmpty()) {
    collect(files)
}
if files:
    collect(files)
if (files.length) {
    collect(files);
}
if (files.length) {
    collect(files);
}

Confusing predicate

Use the positive form in a predicate call when it is a single expression and the calling function can be inverted.

Before

person.takeUnless { it.name != null }

After

person.takeIf { it.name == null }

Deprecated identity

Use structural equality instead of referential equality when comparing with primitive values. In Kotlin, null is included in the set of primitive values.

Before

user.takeUnless { it.name === null }
if len(user.addresses) is 1:
    continue

After

user.takeUnless { it.name == null }
if len(user.addresses) == 1:
    continue

Redundant equality

Compare primitives with identity operator ===.

Before

if (total == 0) {
    return
}
if (total == 0) {
    return;
}
if (total == 0) {
    return;
}

After

if (total === 0) {
    return
}
if (total === 0) {
    return;
}
if (total === 0) {
    return;
}

Redundant equals

Use explicit operator instead of named function in Groovy.

Before

if (total.equals(0)) {
    return
}

After

if (total == 0) {
    return
}

Formatting

Empty file

Empty files should be removed. JVM source files with only package declaration is considered empty.

Before

package awesome.company;
package awesome.company
package awesome.company



File size

File length should not be longer than 1.000 lines of code. If a file exceeds the limit, it should be split into multiple files.

Before

final class Articles {
    static int create(Article article) { /*...*/ }

    static Article read(int articleId) { /*...*/ }

    static void update(int articleId, Article article) { /*...*/ }

    static void delete(int articleId) { /*...*/ }
}
final class Articles {
    static def create(Article article) { /*...*/ }

    static def read(int articleId) { /*...*/ }

    static def update(int articleId, Article article) { /*...*/ }

    static def delete(int articleId) { /*...*/ }
}
object Articles {
    fun create(article: Article): Int { /*...*/ }

    fun read(articleId: Int): Article { /*...*/ }

    fun update(articleId: Int, article: Article) { /*...*/ }

    fun delete(articleId: Int) { /*...*/ }
}
int create_article(Article article) {
    // ...
}

Article read_article(int article_id) {
    // ...
}

void update_article(int article_id, Article article) {
    // ...
}

void delete_article(int article_id) {
    // ...
}
def create_article(article):
    // ...

def read_article(article_id):
    // ...

def update_article(article_id, article):
    // ...

def delete_article(article_id):
    // ...
function createArticle(article) {
    // ...
}

function readArticle(articleId) {
    // ...
}

function updateArticle(articleId, article) {
    // ...
}

function deleteArticle(articleId) {
    // ...
}
function createArticle(article: Article): number {
    // ...
}

function readArticle(articleId: number): Article {
    // ...
}

function updateArticle(articleId: number, article: Article): void {
    // ...
}

function deleteArticle(articleId: number): void {
    // ...
}

After

final class ArticleCreator {
    static int create(Article article) { /*...*/ }
}
final class ArticleReader {
    static Article read(int articleId) { /*...*/ }
}
final class ArticleUpdater {
    static void update(int articleId, Article article) { /*...*/ }
}
final class ArticleDeleter {
    static void delete(int articleId) { /*...*/ }
}

final class ArticleCreator {
    static def create(Article article) { /*...*/ }
}
final class ArticleReader {
    static def read(int articleId) { /*...*/ }
}
final class ArticleUpdater {
    static def update(int articleId, Article article) { /*...*/ }
}
final class ArticleDeleter {
    static def delete(int articleId) { /*...*/ }
}

fun Articles.create(article: Article): Int { /*...*/ }
fun Articles.read(articleId: Int): Article { /*...*/ }
fun Articles.update(articleId: Int, article: Article) { /*...*/ }
fun Articles.delete(articleId: Int) { /*...*/ }

int create_article(Article article) {
    // ...
}
Article read_article(int article_id) {
    // ...
}
void update_article(int article_id, Article article) {
    // ...
}
void delete_article(int article_id) {
    // ...
}

def create_article(article):
    // ...
def read_article(article_id):
    // ...
def update_article(article_id, article):
    // ...
def delete_article(article_id):
    // ...

function createArticle(article) {
    // ...
}
function readArticle(articleId) {
    // ...
}
function updateArticle(articleId, article) {
    // ...
}
function deleteArticle(articleId) {
    // ...
}

function createArticle(article: Article): number {
    // ...
}
function readArticle(articleId: number): Article {
    // ...
}
function updateArticle(articleId: number, article: Article): void {
    // ...
}
function deleteArticle(articleId: number): void {
    // ...
}

Configuration
Setting Default value
FileLength#max 1.000
ClassSize#maxLines 1.000
rulebook_max_file_size 1.000
--max-file-size 1.000
rulebook-max-file-size 1.000
max-lines 1.000
max-lines 1.000

Indent style

Use spaces instead of tabs for indentation.

Before

class Subscriber {
\t void subscribe() {
\t\t publisher.subscribe(this);
\t }
}
class Subscriber {
\t def subscribe() {
\t\t publisher.subscribe(this)
\t }
}
class Subscriber {
\t fun subscribe() {
\t\t publisher.subscribe(this)
\t }
}
class Subscriber {
\t void subscribe() {
\t\t publisher.subscribe(this);
\t }
}
class Subscriber:
\t def subscribe(self):
\t\t publisher.subscribe(self)
class Subscriber {
\t subscribe() {
\t\t publisher.subscribe(this);
\t }
}
class Subscriber {
\t subscribe(): void {
\t\t publisher.subscribe(this);
\t }
}

After

class Subscriber {
    void subscribe() {
        publisher.subscribe(this);
    }
}
class Subscriber {
    def subscribe() {
        publisher.subscribe(this)
    }
}
class Subscriber {
    fun subscribe() {
        publisher.subscribe(this)
    }
}
class Subscriber {
    void subscribe() {
        publisher.subscribe(this);
    }
}
class Subscriber:
    def subscribe(self):
        publisher.subscribe(self)
class Subscriber {
    subscribe() {
        publisher.subscribe(this);
    }
}
class Subscriber {
    subscribe(): void {
        publisher.subscribe(this);
    }
}

Line feed

Apply Unix-style line feed (LF) as a line separator.

Before

class AwesomeImplementation { /*...*/ }\r\n
class AwesomeImplementation { /*...*/ }\r\n
class AwesomeImplementation:
    pass\r\n
class AwesomeImplementation { /*...*/ }\r\n
class AwesomeImplementation { /*...*/ }\r\n

After

class AwesomeImplementation { /*...*/ }\n
class AwesomeImplementation { /*...*/ }\n
class AwesomeImplementation:
    pass\n
class AwesomeImplementation { /*...*/ }\n
class AwesomeImplementation { /*...*/ }\n

Line length

Length of a line should not exceed certain number of characters.

Before

StringBuilder builder = new StringBuilder("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
var builder = new StringBuilder('Lorem ipsum dolor sit amet, consectetur adipiscing elit.')
val builder = StringBuilder("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
std::string builder = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
builder = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
const builder = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
const builder: string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';

After

StringBuilder builder =
    new StringBuilder(
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
    );
var builder =
    new StringBuilder(
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
    )
val builder =
    StringBuilder(
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
    )
std::string builder =
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
builder = \
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
const builder =
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
const builder: string =
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
Configuration
Setting Default value
LineLength#max 100
LineLength#length 100
rulebook_max_line_length 100
--max-line-length 100
rulebook-max-line-length 100
max-len 100
max-len 100

Trailing newline

End files with a newline character.

Before

class AwesomeImplementation { /*...*/ }
class AwesomeImplementation { /*...*/ }
class AwesomeImplementation { /*...*/ }
class AwesomeImplementation { /*...*/ }
class AwesomeImplementation:
    pass
class AwesomeImplementation { /*...*/ }
class AwesomeImplementation { /*...*/ }

After

class AwesomeImplementation { /*...*/ }
\n
class AwesomeImplementation { /*...*/ }
\n
class AwesomeImplementation { /*...*/ }
\n
class AwesomeImplementation { /*...*/ }
\n
class AwesomeImplementation:
    pass
\n
class AwesomeImplementation { /*...*/ }
\n
class AwesomeImplementation { /*...*/ }
\n

Unnecessary trailing space

A line should not end with a whitespace character.

Before

class AwesomeImplementation { /*...*/ } \n
class AwesomeImplementation { /*...*/ } \n
class AwesomeImplementation { /*...*/ } \n
class AwesomeImplementation { /*...*/ } \n
class AwesomeImplementation:
    pass \n
class AwesomeImplementation { /*...*/ } \n
class AwesomeImplementation { /*...*/ } \n

After

class AwesomeImplementation { /*...*/ }\n
class AwesomeImplementation { /*...*/ }\n
class AwesomeImplementation { /*...*/ }\n
class AwesomeImplementation { /*...*/ }\n
class AwesomeImplementation:
    pass\n
class AwesomeImplementation { /*...*/ }\n
class AwesomeImplementation { /*...*/ }\n

Naming

Abbreviation as word

Ensures that the first letter of acronyms longer than three characters are always capitalized.

Before

class RestAPI {
    String httpURL = "https://example.com";
}
class RestAPI {
    var httpURL = 'https://example.com'
}
class RestAPI {
    val httpURL = "https://example.com"
}
class RestAPI {
    std::string httpURL = "https://example.com";
}
class RestAPI:
    http_url = 'https://example.com'
class RestAPI {
    httpURL: string = 'https://example.com';
}

After

class RestApi {
    String httpUrl = "https://example.com";
}
class RestApi {
    var httpUrl = 'https://example.com'
}
class RestApi {
    val httpUrl = "https://example.com"
}
class RestApi {
    std::string http_url = "https://example.com";
}
class RestApi:
    http_url = 'https://example.com'
class RestApi {
    httpUrl: string = 'https://example.com';
}

Boolean property interoperability

Kotlin field definitions that are Boolean types should be prefixed with is. Otherwise, the compiler will generate a getter method with get prefix.

Before

val active: Boolean
boolean getActive() {}

After

val isActive: Boolean
boolean isActive() {}

Class name

Class, interface and object names are written in PascalCase.

Before

class train_station {}
class train_station {}
class train_station
class train_station {};
class train_station:
    pass

After

class TrainStation {}
class TrainStation {}
class TrainStation
class TrainStation {};
class TrainStation:
    pass

Constant name

Constant fields should be written in SCREAMING_SNAKE_CASE.

Before

static final int maxValue = 99;
static final var maxValue = 99
const val maxValue = 99
const maxValue: number = 99;

After

static final int MAX_VALUE = 99;
static final var MAX_VALUE = 99
const val MAX_VALUE = 99
const MAX_VALUE: number = 99;

File name

If the file contains a single class, the file name should be the same as the root class name.

Before

└─ com.example
   └─ UserObject.java
      └─ class User {}
└─ com.example
   └─ UserObject.groovy
      └─ class User {}
└─ com.example
   └─ UserObject.kt
      └─ class User
└─ com.example
   └─ UserObject.cpp
      └─ class User {};
└─ com.example
   └─ user_object.py
      └─ class User:
          pass
└─ com.example
   └─ UserObject.js
      └─ class User {}
└─ com.example
   └─ UserObject.ts
      └─ class User {}

After

└─ com.example
   └─ User.java
      └─ class User {}
└─ com.example
   └─ User.groovy
      └─ class User {}
└─ com.example
   └─ User.kt
      └─ class User
└─ com.example
   └─ User.cpp
      └─ class User {};
└─ com.example
   └─ user.py
      └─ class User:
          pass
└─ com.example
   └─ User.js
      └─ class User {}
└─ com.example
   └─ User.ts
      └─ class User {}

Generic name

Generic type parameters should be named with a single uppercase letter. This rule is ignored when there are multiple generic type parameters in the same declaration.

Before

class Box<Element> {}

void <Type> rotate(Box<Type> box) {}
class Box<Element> {}

void <Type> rotate(Box<Type> box) {}
class Box<Element>() {}

fun <Type> rotate(box: Box<Type>) {}
template <typename Element>
class Box {};

template <typename Type>
void rotate(Box<Type> box) {}
from typing import TypeVar

Element = TypeVar('Element')
Type = TypeVar('Type')


class Box(Element):
    pass


def rotate(box: Box[Type]):
    pass
class Box<Element> {}

function rotate<Type>(box: Box<Type>): void {}

After

class Box<E> {}

void <T> rotate(Box<T> box) {}
class Box<E> {}

void <T> rotate(Box<T> box) {}
class Box<E>() {}

fun <T> rotate(box: Box<T>) {}
template <typename E>
class Box {};

template <typename T>
void rotate(Box<T> box) {}
from typing import TypeVar

E = TypeVar('E')
T = TypeVar('T')


class Box(E):
    pass


def rotate(box: Box[T]):
    pass
class Box<E> {}

function rotate<T>(box: Box<T>): void {}

Identifier name

Non-constant fields, functions and parameters should be written in camelCase. In Python and C/C++, the snake_case style is used instead.

Before

void DebugUser(User User) {
    User AnotherUser = User;
}
def DebugUser(User User) {
    var AnotherUser = User
}
fun DebugUser(User: User) {
    val AnotherUser = User
}
void DebugUser(User User) {
    User AnotherUser = User;
}
def DebugUser(User):
    AnotherUser = User
function DebugUser(User: User): void {
    const AnotherUser: User = User;
}

After

void debugUser(User user) {
    User anotherUser = user;
}
def debugUser(User user) {
    var anotherUser = user
}
fun debugUser(user: User) {
    val anotherUser = user
}
void debug_user(User user) {
    User another_user = user;
}
def debug_user(user):
    another_user = user
function debugUser(user: User): void {
    const anotherUser: User = user;
}

Illegal variable name

Prohibits primitive type names, base Object type names and their plural forms as identifiers of properties, parameters and local variables. The name of the identifier should be descriptive and meaningful.

Before

String string;

List<Person> list;
var string

var list
val string: String

val list: List<Person>
std::string string;

std::vector<Person> list;
string: str

list: list[Person]
let string;

let list;
let string: string;

let list: Person[];

After

String name;

List<Person> people;
var name

var people
val name: String

val people: List<Person>
std::string name;

std::vector<Person> people;
name: str

people: list[Person]
let name;

let people;
let name: string;

let people: Person[];
Configuration
Setting Default value
IllegalIdentifierName#format object, integer, string, objects, integers, strings
IllegalVariableName#names object, integer, string, object, integers, strings
rulebook_illegal_variable_names any, boolean, byte, char, double, float, int, long, short, string, many, booleans, bytes, chars, doubles, floats, ints, longs, shorts
--illegal-variable-names integer, string, integers, strings
bad-names objs, ints, strs
id-denylist error, object, number, string, objects, numbers, strings
id-denylist error, object, number, string, objects, numbers, strings

Meaningless word

Prohibits meaningless source names in class, interface, object and files. The name of utility classes (or files) should be the plural form of the extended class.

Before

class SpaceshipWrapper {}
class SpaceshipWrapper {}
class SpaceshipWrapper
class SpaceshipWrapper {};
class SpaceshipWrapper():
    pass
class SpaceshipWrapper {}
class SpaceshipWrapper {}

After

class Spaceship {}
class Spaceship {}
class Spaceship
class Spaceship {};
class Spaceship():
    pass
class Spaceship {}
class Spaceship {}
Configuration
Setting Default value
MeaninglessWord#words Util, Utility, Helper, Manager, Wrapper
MeaninglessWord#words Util, Utility, Helper, Manager, Wrapper
rulebook_meaningless_words Util, Utility, Helper, Manager, Wrapper
--meaningless-words Util, Utility, Helper, Manager, Wrapper
rulebook-meaningless-words Util, Utility, Helper, Manager, Wrapper

Package name

Package names should be written in lowercase with no separators. In C++, namespaces are considered as packages.

Before

package com.example.user_management;
package com.example.user_management
package com.example.user_management
namespace com {
    namespace example {
        namespace user_management {
            // ...
        }
    }
}
└─ UserManagement
   └─ user_config.py

After

package com.example.usermanagement;
package com.example.usermanagement
package com.example.usermanagement
namespace com {
    namespace example {
        namespace usermanagement {
            // ...
        }
    }
}
└─ user_management
   └─ user_config.py

Ordering

Block tag order

Block tags should be ordered in the following sequence: @constructor, @receiver, @param, @property, @return, @throws, @see.

Before

/**
 * @see User
 * @return The user object.
 * @param name The name of the user.
 */
abstract User createUser(String name);
/**
 * @see User
 * @return The user object.
 * @param name The name of the user.
 */
abstract def createUser(String name)
/**
 * @see User
 * @return The user object.
 * @param name The name of the user.
 */
abstract fun createUser(name: String): User
/**
 * @see User
 * @return The user object.
 * @param name The name of the user.
 */
function createUser(name) {}
/**
 * @see User
 * @return The user object.
 * @param name The name of the user.
 */
function createUser(name: string): User {}

After

/**
 * @param name The name of the user.
 * @return The user object.
 * @see User
 */
abstract User createUser(String name);
/**
 * @param name The name of the user.
 * @return The user object.
 * @see User
 */
abstract def createUser(String name)
/**
 * @param name The name of the user.
 * @return The user object.
 * @see User
 */
abstract fun createUser(name: String): User
/**
 * @param name The name of the user.
 * @return The user object.
 * @see User
 */
function createUser(name) {}
/**
 * @param name The name of the user.
 * @return The user object.
 * @see User
 */
function createUser(name: string): User {}

Common function position

Place Object built-in methods such as toString(), hashCode() and equals() at the end of the class.

Before

class Notification {
    private String message;

    public Notification(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return message;
    }

    public void notify() {
        return System.out.println(message);
    }
}
class Notification {
    private var message

    public Notification(String message) {
        this.message = message
    }

    @Override
    public def toString() {
        return message
    }

    public def notify() {
        println(message)
    }
}
class Notification(private val message: String) {
    public override fun toString(): String = message

    public fun notify() {
        println(message)
    }
}
class Notification:
    def __init__(self, message):
        self.message = message
        self.id = randomize()

    def __str__(self):
        return self.message

    def notify(self):
        print(self.message)
class Notification {
    constructor(message) {
        this.message = message;
    }

    toString() {
        return this.message;
    }

    notify() {
        console.log(this.message);
    }
}
class Notification {
    constructor(message: string) {
        this.message = message;
    }

    toString(): string {
        return this.message;
    }

    notify(): void {
        console.log(this.message);
    }
}

After

class Notification {
    private String message;

    public Notification(String message) {
        this.message = message;
    }

    public void notify() {
        return System.out.println(message);
    }

    @Override
    public String toString() {
        return message;
    }
}
class Notification {
    private var message

    public Notification(String message) {
        this.message = message
    }

    public def notify() {
        println(message)
    }

    @Override
    public def toString() {
        return message
    }
}
class Notification(private val message: String) {
    public fun notify() {
        println(message)
    }

    public override fun toString(): String = message
}
class Notification:
    def __init__(self, message):
        self.message = message
        self.id = randomize()

    def notify(self):
        print(self.message)

    def __str__(self):
        return self.message
class Notification {
    constructor(message) {
        this.message = message;
    }

    notify() {
        console.log(this.message);
    }

    toString() {
        return this.message;
    }
}
class Notification {
    constructor(message: string) {
        this.message = message;
    }

    notify(): void {
        console.log(this.message);
    }

    toString(): string {
        return this.message;
    }
}

Import order

Import directives should be ordered alphabetically without any blank lines.

Before

import java.util.List;

import com.example.User;
import java.util.List

import com.example.User
import java.util.List

import com.example.User
#include "user.h"

#include <vector>
import utils

import user
import { Utils } from './utils';

import { User } from './user';
import { Utils } from './utils';

import { User } from './user';

After

import com.example.User;
import java.util.List;
import com.example.User
import java.util.List
import com.example.User
import java.util.List
#include <vector>
#include "user.h"
import user
import utils
import { User } from './user';
import { Utils } from './utils';
import { User } from './user';
import { Utils } from './utils';

Inner class position

Place inner classes at the end of the class.

Before

class Article {
    class Author {}

    Article(String content, Author author) {}

    Article(String content) {}
}
class Article {
    class Author {}

    Article(String content, Author author) {}

    Article(String content) {}
}
class Article(content: String, author: Author) {
    class Author(name: String)

    constructor(content: String) : this(content, null)
}
class Article {
    class Author {};

    Article(std::string content, Author author) {}

    Article(std::string content) {}
}
class Article:
    class Author:
        pass

    def __init__(self, content, author = None):
        pass
class Article {
    class Author {}

    constructor(content, author) {}

    constructor(content) {}
}
class Article {
    class Author {}

    constructor(content: string, author: Author) {}

    constructor(content: string) {}
}

After

class Article {
    Article(String content, Author author) {}

    Article(String content) {}

    class Author {}
}
class Article {
    Article(String content, Author author) {}

    Article(String content) {}

    class Author {}
}
class Article(content: String, author: Author) {
    constructor(content: String) : this(content, null)

    class Author(name: String)
}
class Article {
    Article(std::string content, Author author) {}

    Article(std::string content) {}

    class Author {};
}
class Article:
    def __init__(self, content, author = None):
        pass

    class Author:
        pass
class Article {
    constructor(content, author) {}

    constructor(content) {}

    class Author {}
}
class Article {
    constructor(content: string, author: Author) {}

    constructor(content: string) {}

    class Author {}
}

Member order

The class should be organized as follows: properties, initializer block, constructors, methods and static members. Inner classes should be declared next to the last member that uses them.

Before

class Car {
    static void log(String message) {
        System.out.println(message);
    }

    Car(String brand, String model) {}

    Car(String brand) {
        this(brand, "Unknown");
    }

    int wheels = 4;

    void start() {
        log("Car created");
    }
}
class Car {
    static def log(String message) {
        System.out.println(message)
    }

    Car(String brand, String model) {}

    Car(String brand) {
        this(brand, 'Unknown')
    }

    var wheels = 4

    def start() {
        log('Car created')
    }
}
class Car(brand: String, model: String) {
    companion object {
        fun log(message: String) {
            println(message)
        }
    }

    init {
        log("Car created")
    }

    constructor(brand: String) : this(brand, "Unknown")

    val wheels = 4

    fun start() {
        log("Car started")
    }
}
class Car {
    static void log(std::string message) {
        std::cout << message << std::endl;
    }

    Car(std::string brand, std::string model) {}

    Car(std::string brand) : Car(brand, "Unknown") {}

    int wheels = 4;

    void start() {
        log("Car created");
    }
}
class Car:
    @staticmethod
    def log(message: str):
        print(message)

    def __init__(self, brand, model = 'Unknown'):
        pass

    wheels = 4

    def start(self):
        log('Car started')
class Car {
    static log(message) {
        console.log(message);
    }

    constructor(brand, model) {}

    constructor(brand) {
        this(brand, 'Unknown');
    }

    wheels = 4;

    start() {
        Car.log('Car created');
    }
}
class Car {
    static log(message: string): void {
        console.log(message);
    }

    constructor(brand: string, model: string) {}

    constructor(brand: string) {
        this(brand, 'Unknown');
    }

    wheels: number = 4;

    start(): void {
        Car.log('Car created');
    }
}

After

class Car {
    int wheels = 4;

    Car(String brand, String model) {}

    Car(String brand) {
        this(brand, "Unknown");
    }

    void start() {
        log("Car created");
    }

    static void log(String message) {
        System.out.println(message);
    }
}
class Car {
    var wheels = 4

    Car(String brand, String model) {}

    Car(String brand) {
        this(brand, 'Unknown')
    }

    def start() {
        log('Car created')
    }

    static def log(String message) {
        System.out.println(message)
    }
}
class Car(brand: String, model: String) {
    override val wheels = 4

    init {
        log("Car created")
    }

    constructor(brand: String) : this(brand, "Unknown")

    fun start() {
        log("Car started")
    }

    companion object {
        fun log(message: String) {
            println(message)
        }
    }
}
class Car {
    int wheels = 4;

    Car(std::string brand, std::string model) {}

    Car(std::string brand) : Car(brand, "Unknown") {}

    void start() {
        log("Car created");
    }

    static void log(std::string message) {
        std::cout << message << std::endl;
    }
}
class Car:
    wheels = 4

    def __init__(self, brand, model = 'Unknown'):
        pass

    def start(self):
        log('Car started')

    @staticmethod
    def log(message: str):
        print(message)
class Car {
    wheels = 4;

    constructor(brand, model) {}

    constructor(brand) {
        this(brand, 'Unknown');
    }

    start() {
        Car.log('Car created');
    }

    static log(message) {
        console.log(message);
    }
}
class Car {
    wheels: number = 4;

    constructor(brand: string, model: string) {}

    constructor(brand: string) {
        this(brand, 'Unknown');
    }

    start(): void {
        Car.log('Car created');
    }

    static log(message: string): void {
        console.log(message);
    }
}
Configuration
Setting Default value
MemberOrder#order property, constructor, function, static
MemberOrder#order property, constructor, function, static
rulebook_member_order property, initializer, constructor, function, companion
--member-order property, constructor, function, static
rulebook-member-order property, constructor, function, static
sort-class-members property, constructor, function, static
sort-class-members property, constructor, function, static

Modifier order

Visibility modifiers first, followed by abstraction modifiers, then other modifiers.

Before

abstract public class Beacon {
    final static int MAX_RANGE = 100;
}
abstract public class Beacon {
    final static var MAX_RANGE = 100
}
abstract public class Beacon {
    companion object {
        const val MAX_RANGE = 100
    }
}

After

public abstract class Beacon {
    static final int MAX_RANGE = 100;
}
public abstract class Beacon {
    static final var MAX_RANGE = 100
}
public abstract class Beacon {
    companion object {
        const val MAX_RANGE = 100
    }
}

Named import order

Multiple import directives from the same package should be ordered alphabetically.

Before

from utils import validate, parse, format
import { validate, parse, format } from './utils';
import { validate, parse, format } from './utils';

After

from utils import format, parse, validate
import { format, parse, validate } from './utils';
import { format, parse, validate } from './utils';

Overload function position

Place overloaded functions next to each other.

After

int sum(int a, int b) {
    return a + b;
}

int times(int a, int b) {
    return a * b;
}

int sum(int a, int b, int c) {
    return a + b + c;
}
def sum(int a, int b) {
    return a + b
}

def times(int a, int b) {
    return a * b
}

def sum(int a, int b, int c) {
    return a + b + c
}
fun sum(a: Int, b: Int): Int = a + b

fun times(a: Int, b: Int): Int = a * b

fun sum(a: Int, b: Int, c: Int): Int = a + b + c
function sum(a, b) {
    return a + b;
}

function times(a, b) {
    return a * b;
}

function sum(a, b, c) {
    return a + b + c;
}
function sum(a: number, b: number): number {
    return a + b;
}

function times(a: number, b: number): number {
    return a * b;
}

function sum(a: number, b: number, c: number): number {
    return a + b + c;
}

After

int sum(int a, int b) {
    return a + b;
}

int sum(int a, int b, int c) {
    return a + b + c;
}

int times(int a, int b) {
    return a * b;
}
def sum(int a, int b) {
    return a + b
}

def sum(int a, int b, int c) {
    return a + b + c
}

def times(int a, int b) {
    return a * b
}
fun sum(a: Int, b: Int): Int = a + b

fun sum(a: Int, b: Int, c: Int): Int = a + b + c

fun times(a: Int, b: Int): Int = a * b
function sum(a, b) {
    return a + b;
}

function sum(a, b, c) {
    return a + b + c;
}

function times(a, b) {
    return a * b;
}
function sum(a: number, b: number): number {
    return a + b;
}

function sum(a: number, b: number, c: number): number {
    return a + b + c;
}

function times(a: number, b: number): number {
    return a * b;
}

Static import position

Static import directives are to be placed before non-static imports, separated by a blank line.

Before

import java.util.List;

import static java.lang.Math.PI;
import java.util.List

import static java.lang.Math.PI

After

import static java.lang.Math.PI;

import java.util.List;
import static java.lang.Math.PI

import java.util.List

Scripting

Decentralized dependency

Declare dependencies in a centralizeed version catalog file and refer to them by their alias in the build script.

Before

dependencies.implementation 'org.apache.commons:commons-lang3:3.12.0'
dependencies.implementation("org.apache.commons:commons-lang3:3.12.0")

After

dependencies.implementation libs.commons.lang3
dependencies.implementation(libs.commons.lang3)

Eager API

Prefer eager calls over lazy ones.

Before

tasks.findByName('compileJava') {
    println 'Compilation completed'
}
tasks.findByName("compileJava") {
    println("Compilation completed")
}

After

tasks.named('compileJava') {
    println 'Compilation completed'
}
tasks.named("compileJava") {
    println("Compilation completed")
}

Lonely configuration

Avoid opening a scope for a single configuration.

Before

repositories {
    mavenCentral()
}
repositories {
    mavenCentral()
}

After

repositories.mavenCentral()
repositories.mavenCentral()

Root project name

Specify the root project name in settings.gradle or settings.gradle.kts.

After

rootProject.name = 'my-app'
rootProject.name = "my-app"

Script file name

Script file names are in lowercase with words separated by hyphens.

Before

└─ publish_site.gradle
└─ publish_site.gradle.kts

After

└─ publish-site.gradle
└─ publish-site.gradle.kts

Spacing

Block comment spaces

Ensures that block comments starts and ends with a whitespace. In multiline comments, each line after the asterisk should be indented by a whitespace.

Before

/**Pass on user behavior.*/
void report() {}
/**Pass on user behavior.*/
def report() {}
/**Pass on user behavior.*/
fun report()
/**Pass on user behavior.*/
void report() {}
/**Pass on user behavior.*/
function report() {}
/**Pass on user behavior.*/
function report(): void {}

After

/** Pass on user behavior. */
void report() {}
/** Pass on user behavior. */
def report() {}
/** Pass on user behavior. */
fun report()
/** Pass on user behavior. */
void report() {}
/** Pass on user behavior. */
function report() {}
/** Pass on user behavior. */
function report(): void {}

Block tag indentation

Multi-line block tag descriptions should be indented by four spaces, or five spaces from the leading asterisk.

Before

/**
 * @param num the number to return
 * the absolute value for.
 */
void abs(int num) {}
/**
 * @param num the number to return
 * the absolute value for.
 */
def abs(int num) {}
/**
 * @param num the number to return
 * the absolute value for.
 */
fun abs(num: Int): Int
/**
 * @param num the number to return
 * the absolute value for.
 */
void abs(int num) {}
/**
 * @param num the number to return
 * the absolute value for.
 */
function abs(num) {}
/**
 * @param num the number to return
 * the absolute value for.
 */
function abs(num: number): number {}

After

/**
 * @param num the number to return
 *     the absolute value for.
 */
void abs(int num) {}
/**
 * @param num the number to return
 *     the absolute value for.
 */
def abs(int num) {}
/**
 * @param num the number to return
 *     the absolute value for.
 */
fun abs(num: Int): Int
/**
 * @param num the number to return
 *     the absolute value for.
 */
void abs(int num) {}
/**
 * @param num the number to return
 *     the absolute value for.
 */
function abs(num) {}
/**
 * @param num the number to return
 *     the absolute value for.
 */
function abs(num: number): number {}

Case separator

Multiline switch-case entries end with a blank line while short entries are joined.

Before

switch (event) {
    case CANCELLED:
        return;

    case PAST:
        String message = "Event is in the past";
        throw new IllegalStateException(message);
    default:
        createEvent(event);
}
switch (event) {
    case CANCELLED:
        return

    case PAST:
        var message = 'Event is in the past'
        throw new IllegalStateException(message)
    default:
        createEvent(event)
}
when {
    event.isCancelled() -> return

    event.date < now -> {
        val message = "Event is in the past"
        throw IllegalStateException(message)
    }
    else -> createEvent(event)
}
switch (event) {
    case CANCELLED:
        return;

    case PAST: {
        std::string message = "Event is in the past";
        throw std::logic_error(message);
    }
    default:
        create_event(event);
}
match event:
    case CANCELLED:
        return

    case PAST:
        message = 'Event is in the past'
        raise ValueError(message)
    case _:
        create_event(event)
switch (event) {
    case CANCELLED:
        return;

    case PAST: {
        const message = 'Event is in the past';
        throw new Error(message);
    }
    default:
        createEvent(event);
}
switch (event) {
    case CANCELLED:
        return;

    case PAST: {
        const message = 'Event is in the past';
        throw new Error(message);
    }
    default:
        createEvent(event);
}

After

switch (event) {
    case CANCELLED:
        return;

    case PAST:
        String message = "Event is in the past";
        throw new IllegalStateException(message);

    default:
        createEvent(event);
}
switch (event) {
    case CANCELLED:
        return

    case PAST:
        var message = 'Event is in the past'
        throw new IllegalStateException(message)

    default:
        createEvent(event)
}
when {
    event.isCancelled() -> return

    event.date < now -> {
        val message = "Event is in the past"
        throw IllegalStateException(message)
    }

    else -> createEvent(event)
}
switch (event) {
    case CANCELLED:
        return;

    case PAST: {
        std::string message = "Event is in the past";
        throw std::logic_error(message);
    }

    default:
        create_event(event);
}
match event:
    case CANCELLED:
        return

    case PAST:
        message = 'Event is in the past'
        raise ValueError(message)

    case _:
        create_event(event)
switch (event) {
    case CANCELLED:
        return;

    case PAST: {
        const message = 'Event is in the past';
        throw new Error(message);
    }

    default:
        createEvent(event);
}
switch (event) {
    case CANCELLED:
        return;

    case PAST: {
        const message = 'Event is in the past';
        throw new Error(message);
    }

    default:
        createEvent(event);
}

Comment spaces

End-of-file comments should be separated by a single whitespace from the preceding code, and start with a single whitespace.

Before

System.out.println("This is a code");//This is a comment
println('This is a code')//This is a comment
println("This is a code")//This is a comment
std::cout << "This is a code" << std::endl;//This is a comment
print('This is a code')#This is a comment
console.log('This is a code');//This is a comment
console.log('This is a code');//This is a comment

After

System.out.println("This is a code"); // This is a comment
println('This is a code') // This is a comment
println("This is a code") // This is a comment
std::cout << "This is a code" << std::endl; // This is a comment
print('This is a code')  # This is a comment
console.log('This is a code'); // This is a comment
console.log('This is a code'); // This is a comment

Warning

PEP8 requires leading two spaces for comments.

Member separator

Class, function and property declarations should be separated by a blank line. There is an exception for a group of properties.

Before

interface Vehicle {
    int getWheels();
    void start();
}
interface Vehicle {
    def getWheels();
    def start();
}
interface Vehicle {
    val wheels: Int
    fun start()
}
class Vehicle {
    int get_wheels();
    void start();
}
class Vehicle:
    wheels: int
    def start(self):
        pass
class Vehicle {
    getWheels() {}
    start() {}
}
class Vehicle {
    getWheels(): number {}
    start(): void {}
}

After

interface Vehicle {
    int getWheels();

    void start();
}
interface Vehicle {
    def getWheels();

    void start();
}
interface Vehicle {
    val wheels: Int

    fun start()
}
class Vehicle {
    int get_wheels();

    void start();
}
class Vehicle:
    wheels: int

    def start(self):
        pass
class Vehicle {
    getWheels() {}

    start() {}
}
class Vehicle {
    getWheels(): number {}

    start(): void {}
}

Missing blank line before block tags

Separate block tag group from the summary with a blank line.

Before

/**
 * Returns the absolute value of the given number.
 * @param number The number to return the absolute value for.
 * @return The absolute value.
 */
void abs(int number) {}
/**
 * Returns the absolute value of the given number.
 * @param number The number to return the absolute value for.
 * @return The absolute value.
 */
def abs(int number) {}
/**
 * Returns the absolute value of the given number.
 * @param number The number to return the absolute value for.
 * @return The absolute value.
 */
fun abs(number: Int): Int
/**
 * Returns the absolute value of the given number.
 * @param number The number to return the absolute value for.
 * @return The absolute value.
 */
function abs(number) {}
/**
 * Returns the absolute value of the given number.
 * @param number The number to return the absolute value for.
 * @return The absolute value.
 */
function abs(number: number): number {}

After

/**
 * Returns the absolute value of the given number.
 *
 * @param number The number to return the absolute value for.
 * @return The absolute value.
 */
void abs(int number) {}
/**
 * Returns the absolute value of the given number.
 *
 * @param number The number to return the absolute value for.
 * @return The absolute value.
 */
def abs(int number) {}
/**
 * Returns the absolute value of the given number.
 *
 * @param number The number to return the absolute value for.
 * @return The absolute value.
 */
fun abs(number: Int): Int
/**
 * Returns the absolute value of the given number.
 *
 * @param number The number to return the absolute value for.
 * @return The absolute value.
 */
function abs(number) {}
/**
 * Returns the absolute value of the given number.
 *
 * @param number The number to return the absolute value for.
 * @return The absolute value.
 */
function abs(number: number): number {}

Stating

Complicated assignment

Use shorthand assignment operators when the variable being assigned is also used in the expression.

Before

int count = 0;
count = count + 1;
var count = 0
count = count + 1
var count = 0
count = count + 1
int count = 0;
count = count + 1;
count = 0
count = count + 1
let count = 0;
count = count + 1;
let count: number = 0;
count = count + 1;

After

int count = 0;
count += 1;
var count = 0
count += 1
var count = 0
count += 1
int count = 0;
count += 1;
count = 0
count += 1
let count = 0;
count += 1;
let count: number = 0;
count += 1;

Illegal catch

Catch specific exception subclass instead of the generic Throwable, Exception or Error.

Before

try {
    unsafeOperation();
} catch (Throwable e) {
    e.printStackTrace();
}
try {
    unsafeOperation()
} catch (Throwable e) {
    e.printStackTrace()
}
try {
    unsafe_operation();
} catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
}
try:
    unsafe_operation()
except Exception as e:
    print(e)

After

try {
    unsafeOperation();
} catch (IOException | SQLException e) {
    e.printStackTrace();
}
try {
    unsafeOperation()
} catch (IOException | SQLException e) {
    e.printStackTrace()
}
try {
    unsafe_operation();
} catch (std::ios_base::failure& e) {
    std::cerr << e.what() << std::endl;
}
try:
    unsafe_operation()
except (IOError, OSError) as e:
    print(e)

Illegal throw

Throw a narrower exception type instead of Exception, Error or Throwable.

Before

throw new Exception();
throw new Exception()
throw Exception()
throw std::exception();
raise Exception()

After

throw new IllegalStateException();
throw new IllegalStateException()
throw IllegalStateException()
throw std::logic_error("Illegal state");
raise ValueError()

Lonely case

If a switch statement has single branch, it should be replaced with an if statement.

Before

switch (token) {
    case VALUE_TOKEN:
        callback(token);
}
switch (token) {
    case VALUE_TOKEN:
        callback(token)
}
when (token) {
    is Token.ValueToken -> callback(token)
}
switch (token) {
    case VALUE_TOKEN:
        callback(token);
}
match token:
    case Token.VALUE_TOKEN:
        callback(token)
switch (token) {
    case VALUE_TOKEN:
        callback(token);
}
switch (token) {
    case VALUE_TOKEN:
        callback(token);
}

After

if (token == Token.VALUE_TOKEN) {
    callback(token);
}
if (token == Token.VALUE_TOKEN) {
    callback(token)
}
if (token is Token.ValueToken) {
    callback(token)
}
if (token == VALUE_TOKEN) {
    callback(token);
}
if token == Token.VALUE_TOKEN:
    callback(token)
if (token == VALUE_TOKEN) {
    callback(token);
}
if (token == VALUE_TOKEN) {
    callback(token);
}

Lonely if

A single if statement in an else block should be merged with the parent if statement.

Before

if (validateCart(cart)) {
    processPayment(credentials);
} else {
    if (cart.isEmpty()) {
        showEmptyCartError();
    } else {
        showError();
    }
}
if (validateCart(cart)) {
    processPayment(credentials)
} else {
    if (cart.isEmpty()) {
        showEmptyCartError()
    } else {
        showError()
    }
}
if (validateCart(cart)) {
    processPayment(credentials)
} else {
    if (cart.isEmpty()) {
        showEmptyCartError()
    } else {
        showError()
    }
}
if (validate_cart(cart)) {
    process_payment(credentials);
} else {
    if (cart.is_empty()) {
        show_empty_cart_error();
    } else {
        show_error();
    }
}
if validate_cart(cart):
    process_payment(credentials)
else:
    if not cart:
        show_empty_cart_error()
    else:
        show_error()
if (validateCart(cart)) {
    processPayment(credentials);
} else {
    if (cart.isEmpty()) {
        showEmptyCartError();
    } else {
        showError();
    }
}
if (validateCart(cart)) {
    processPayment(credentials);
} else {
    if (cart.isEmpty()) {
        showEmptyCartError();
    } else {
        showError();
    }
}

After

if (validateCart(cart)) {
    processPayment(credentials);
} else if (cart.isEmpty()) {
    showEmptyCartError();
} else {
    showError();
}
if (validateCart(cart)) {
    processPayment(credentials)
} else if (cart.isEmpty()) {
    showEmptyCartError()
} else {
    showError()
}
if (validateCart(cart)) {
    processPayment(credentials)
} else if (cart.isEmpty()) {
    showEmptyCartError()
} else {
    showError()
}
if (validate_cart(cart)) {
    process_payment(credentials);
} else if (cart.is_empty()) {
    show_empty_cart_error();
} else {
    show_error();
}
if validate_cart(cart):
    process_payment(credentials)
elif not cart:
    show_empty_cart_error()
else:
    show_error()
if (validateCart(cart)) {
    processPayment(credentials);
} else if (cart.isEmpty()) {
    showEmptyCartError();
} else {
    showError();
}
if (validateCart(cart)) {
    processPayment(credentials);
} else if (cart.isEmpty()) {
    showEmptyCartError();
} else {
    showError();
}

Missing braces

Enforces the use of braces for multiline if, else, for, while and do statements.

Before

if (validateCart(cart))
    processPayment(credentials);
else
    showError();
if (validateCart(cart))
    processPayment(credentials)
else
    showError()
if (validateCart(cart))
    processPayment(credentials)
else
    showError()
if (validateCart(cart))
    processPayment(credentials);
else
    showError();
if (validateCart(cart))
    processPayment(credentials);
else
    showError();

After

if (validateCart(cart)) {
    processPayment(credentials);
} else {
    showError();
}
if (validateCart(cart)) {
    processPayment(credentials)
} else {
    showError()
}
if (validateCart(cart)) {
    processPayment(credentials)
} else {
    showError()
}
if (validateCart(cart)) {
    processPayment(credentials);
} else {
    showError();
}
if (validateCart(cart)) {
    processPayment(credentials);
} else {
    showError();
}

Nested if-else

If a block ends with an if statement without else and the body is at least 2 lines, it should be inverted to avoid nesting and unnecessary indentation.

Before

void login(User user) {
    if (user.isValid()) {
        if (!isLoggedIn(user)) {
            updateProfile(user);
            displayDashboard();
        }
    }
}
def login(User user) {
    if (user.isValid()) {
        if (!isLoggedIn(user)) {
            updateProfile(user)
            displayDashboard()
        }
    }
}
fun login(user: User) {
    if (user.isValid()) {
        if (!isLoggedIn(user)) {
            updateProfile(user)
            displayDashboard()
        }
    }
}
void login(User user) {
    if (user.is_valid()) {
        if (!is_logged_in(user)) {
            update_profile(user);
            display_dashboard();
        }
    }
}
def login(user):
    if user.is_valid():
        if not is_logged_in(user):
            update_profile(user)
            display_dashboard()
function login(user) {
    if (user.isValid()) {
        if (!isLoggedIn(user)) {
            updateProfile(user);
            displayDashboard();
        }
    }
}
function login(user: User): void {
    if (user.isValid()) {
        if (!isLoggedIn(user)) {
            updateProfile(user);
            displayDashboard();
        }
    }
}

After

void login(User user) {
    if (!user.isValid()) {
        return;
    }
    if (isLoggedIn(user)) {
        return;
    }
    updateProfile(user);
    displayDashboard();
}
def login(User user) {
    if (!user.isValid()) {
        return
    }
    if (isLoggedIn(user)) {
        return
    }
    updateProfile(user)
    displayDashboard()
}
fun login(user: User) {
    if (!user.isValid()) {
        return
    }
    if (isLoggedIn(user)) {
        return
    }
    updateProfile(user)
    displayDashboard()
}
void login(User user) {
    if (!user.is_valid()) {
        return;
    }
    if (is_logged_in(user)) {
        return;
    }
    update_profile(user);
    display_dashboard();
}
def login(user):
    if not user.is_valid():
        return
    if is_logged_in(user):
        return
    update_profile(user)
    display_dashboard()
function login(user) {
    if (!user.isValid()) {
        return;
    }
    if (isLoggedIn(user)) {
        return;
    }
    updateProfile(user);
    displayDashboard();
}
function login(user: User): void {
    if (!user.isValid()) {
        return;
    }
    if (isLoggedIn(user)) {
        return;
    }
    updateProfile(user);
    displayDashboard();
}

Redundant default

If every branch of a switch statement has a continue, return or throw statement, the default branch can be lifted.

Before

void park(Car car) {
    switch (car) {
        case MOVING: throw new IllegalStateException();
        case PARKED: return;
        default: findParking(car);
    }
}
def park(Car car) {
    switch (car) {
        case MOVING: throw new IllegalStateException()
        case PARKED: return
        default: findParking(car)
    }
}
fun park(car: Car) {
    when {
        car.isMoving() -> throw IllegalStateException()
        car.isParked() -> return
        else -> findParking(car)
    }
}
void park(Car car) {
    switch (car) {
        case MOVING: throw IllegalStateException();
        case PARKED: return;
        default: findParking(car);
    }
}
def park(car):
    match car:
        case Car.MOVING: raise ValueError()
        case Car.PARKED: return
        case _: find_parking(car)
function park(car) {
    switch (car) {
        case MOVING: throw new Error();
        case PARKED: return;
        default: findParking(car);
    }
}
function park(car: Car): void {
    switch (car) {
        case MOVING: throw new Error();
        case PARKED: return;
        default: findParking(car);
    }
}

After

void park(Car car) {
    switch (car) {
        case MOVING: throw new IllegalStateException();
        case PARKED: return;
    }
    findParking(car);
}
def park(Car car) {
    switch (car) {
        case MOVING: throw new IllegalStateException()
        case PARKED: return
    }
    findParking(car)
}
fun park(car: Car) {
    when {
        car.isMoving() -> throw IllegalStateException()
        car.isParked() -> return
    }
    findParking(car)
}
void park(Car car) {
    switch (car) {
        case MOVING: throw IllegalStateException();
        case PARKED: return;
    }
    findParking(car);
}
def park(car):
    match car:
        case Car.MOVING: raise ValueError()
        case Car.PARKED: return
    find_parking(car)
function park(car) {
    switch (car) {
        case MOVING: throw new Error();
        case PARKED: return;
    }
    findParking(car);
}
function park(car: Car): void {
    switch (car) {
        case MOVING: throw new Error();
        case PARKED: return;
    }
    findParking(car);
}

Redundant else

When every if and else-if block has a continue, return or throw statement, the else block can be lifted.

Before

void park(Car car) {
    if (car.isMoving()) {
        throw new IllegalStateException();
    } else if (car.isParked()) {
        return;
    } else {
        findParking(car);
    }
}
def park(Car car) {
    if (car.isMoving()) {
        throw new IllegalStateException()
    } else if (car.isParked()) {
        return
    } else {
        findParking(car)
    }
}
fun park(car: Car) {
    if (car.isMoving()) {
        throw IllegalStateException()
    } else if (car.isParked()) {
        return
    } else {
        findParking(car)
    }
}
void park(Car car) {
    if (car.is_moving()) {
        throw IllegalStateException();
    } else if (car.is_parked()) {
        return;
    } else {
        findParking(car);
    }
}
def park(car):
    if car.is_moving():
        raise ValueError()
    elif car.is_parked():
        return
    else:
        find_parking(car)
function park(car) {
    if (car.isMoving()) {
        throw new Error();
    } else if (car.isParked()) {
        return;
    } else {
        findParking(car);
    }
}
function park(car: Car): void {
    if (car.isMoving()) {
        throw new Error();
    } else if (car.isParked()) {
        return;
    } else {
        findParking(car);
    }
}

After

void park(Car car) {
    if (car.isMoving()) {
        throw new IllegalStateException();
    }
    if (car.isParked()) {
        return;
    }
    findParking(car);
}
def park(Car car) {
    if (car.isMoving()) {
        throw new IllegalStateException()
    }
    if (car.isParked()) {
        return
    }
    findParking(car)
}
fun park(car: Car) {
    if (car.isMoving()) {
        throw IllegalStateException()
    }
    if (car.isParked()) {
        return
    }
    findParking(car)
}
void park(Car car) {
    if (car.is_moving()) {
        throw IllegalStateException();
    }
    if (car.is_parked()) {
        return;
    }
    findParking(car);
}
def park(car):
    if car.is_moving():
        raise ValueError()
    if car.is_parked():
        return
    find_parking(car)
function park(car) {
    if (car.isMoving()) {
        throw new Error();
    }
    if (car.isParked()) {
        return;
    }
    findParking(car);
}
function park(car: Car): void {
    if (car.isMoving()) {
        throw new Error();
    }
    if (car.isParked()) {
        return;
    }
    findParking(car);
}

Redundant if

If-else statement that returns boolean can be simplified by returning the condition.

Before

boolean isValid(User user) {
    if (user.isActive()) {
        return true;
    } else {
        return false;
    }
}
boolean isValid(User user) {
    if (user.isActive()) {
        return true
    } else {
        return false
    }
}
fun isValid(user: User): Boolean {
    if (user.isActive()) {
        return true
    } else {
        return false
    }
}
bool is_valid(User user) {
    if (user.is_active()) {
        return true;
    } else {
        return false;
    }
}
def is_valid(user):
    if user.is_active():
        return True
    else:
        return False
function isValid(user) {
    if (user.isActive()) {
        return true;
    } else {
        return false;
    }
}
function isValid(user: User): boolean {
    if (user.isActive()) {
        return true;
    } else {
        return false;
    }
}

After

boolean isValid(User user) {
    return user.isActive();
}
boolean isValid(User user) {
    return user.isActive()
}
fun isValid(user: User): Boolean {
    return user.isActive()
}
bool is_valid(User user) {
    return user.is_active();
}
def is_valid(user):
    return user.is_active()
function isValid(user) {
    return user.isActive();
}
function isValid(user: User): boolean {
    return user.isActive();
}

Semicolon

Do not use semicolons at the end of statements in languages that do not require them.

Before

sendEmail(user);
sendEmail(user);
send_email(user);
sendEmail(user)
sendEmail(user)

After

sendEmail(user)
sendEmail(user)
send_email(user)
sendEmail(user);
sendEmail(user);

Warning

Semicolons are enforced in JavaScript and TypeScript to prevent issues with automatic semicolon insertion.

Unnecessary continue

The last continue statement in a loop is useless.

Before

for (User user : users) {
    if (user.isActive()) {
        sendEmail(user);
    }
    continue;
}
for (User user : users) {
    if (user.isActive()) {
        sendEmail(user)
    }
    continue
}
for (user in users) {
    if (user.isActive()) {
        sendEmail(user)
    }
    continue
}
for (User user : users) {
    if (user.is_active()) {
        send_email(user);
    }
    continue;
}
for user in users:
    if user.is_active():
        send_email(user)
    continue
for (const user of users) {
    if (user.isActive()) {
        sendEmail(user);
    }
    continue;
}
for (const user of users) {
    if (user.isActive()) {
        sendEmail(user);
    }
    continue;
}

After

for (User user : users) {
    if (user.isActive()) {
        sendEmail(user);
    }
}
for (User user : users) {
    if (user.isActive()) {
        sendEmail(user)
    }
}
for (user in users) {
    if (user.isActive()) {
        sendEmail(user)
    }
}
for (User user : users) {
    if (user.is_active()) {
        send_email(user);
    }
}
for user in users:
    if user.is_active():
        send_email(user)
for (const user of users) {
    if (user.isActive()) {
        sendEmail(user);
    }
}
for (const user of users) {
    if (user.isActive()) {
        sendEmail(user);
    }
}

Unnecessary return

The last return statement in a function is useless.

Before

void sendEmails(List<User> users) {
    for (User user : users) {
        if (user.isActive()) {
            sendEmail(user);
        }
    }
    return;
}
void sendEmails(List<User> users) {
    for (User user : users) {
        if (user.isActive()) {
            sendEmail(user)
        }
    }
    return
}
fun sendEmails(users: List<User>) {
    for (user in users) {
        if (user.isActive()) {
            sendEmail(user)
        }
    }
    return
}
void send_emails(std::vector<User> users) {
    for (User user : users) {
        if (user.is_active()) {
            send_email(user);
        }
    }
    return;
}
def send_emails(users):
    for user in users:
        if user.is_active():
            send_email(user)
    return
function sendEmails(users) {
    for (const user of users) {
        if (user.isActive()) {
            sendEmail(user);
        }
    }
    return;
}
function sendEmails(users: User[]): void {
    for (const user of users) {
        if (user.isActive()) {
            sendEmail(user);
        }
    }
    return;
}

After

void sendEmails(List<User> users) {
    for (User user : users) {
        if (user.isActive()) {
            sendEmail(user);
        }
    }
}
void sendEmails(List<User> users) {
    for (User user : users) {
        if (user.isActive()) {
            sendEmail(user)
        }
    }
}
fun sendEmails(users: List<User>) {
    for (user in users) {
        if (user.isActive()) {
            sendEmail(user)
        }
    }
}
void send_emails(std::vector<User> users) {
    for (User user : users) {
        if (user.is_active()) {
            send_email(user);
        }
    }
}
def send_emails(users):
    for user in users:
        if user.is_active():
            send_email(user)
function sendEmails(users) {
    for (const user of users) {
        if (user.isActive()) {
            sendEmail(user);
        }
    }
}
function sendEmails(users: User[]): void {
    for (const user of users) {
        if (user.isActive()) {
            sendEmail(user);
        }
    }
}

Testing

Complicated assertion

Use targeted assertion methods instead of general ones with complicated conditions.

Before

assertTrue(username == null);
assertTrue(username == null)
assertTrue(username == null)
self.assertTrue(username is None)

After

assertNull(username);
assertNull(username)
assertNull(username)
self.assertIsNone(username)

Confusing assertion

Flip assertions instead of negating conditions.

Before

assertFalse(!user.isActive());
assertFalse(!user.isActive())
assertFalse(!user.isActive())
self.assertFalse(!user.is_active())

After

assertTrue(user.isActive());
assertTrue(user.isActive())
assertTrue(user.isActive())
self.assertTrue(user.is_active())

Deprecated annotation

Prefer Kotlin test annotations over JUnit ones.

Before

import org.junit.Test

class UserTest {
    @Test
    fun testUser() {}
}

After

import kotlin.test.Test

class UserTest {
    @Test
    fun testUser() {}
}

Trimming

Block comment trim

Do not start or end block comments with whitespaces.

Before

/**
 *
 * AUTHOR: John Doe
 * LICENSE: Apache 2.0
 *
 */
/**
 *
 * AUTHOR: John Doe
 * LICENSE: Apache 2.0
 *
 */
/**
 *
 * AUTHOR: John Doe
 * LICENSE: Apache 2.0
 *
 */
/**
 *
 * AUTHOR: John Doe
 * LICENSE: Apache 2.0
 *
 */
"""

AUTHOR: John Doe
LICENSE: Apache 2.0

"""
/**
 *
 * AUTHOR: John Doe
 * LICENSE: Apache 2.0
 *
 */
/**
 *
 * AUTHOR: John Doe
 * LICENSE: Apache 2.0
 *
 */

After

/**
 * AUTHOR: John Doe
 * LICENSE: Apache 2.0
 */
/**
 * AUTHOR: John Doe
 * LICENSE: Apache 2.0
 */
/**
 * AUTHOR: John Doe
 * LICENSE: Apache 2.0
 */
/**
 * AUTHOR: John Doe
 * LICENSE: Apache 2.0
 */
"""
AUTHOR: John Doe
LICENSE: Apache 2.0
"""
/**
 * AUTHOR: John Doe
 * LICENSE: Apache 2.0
 */
/**
 * AUTHOR: John Doe
 * LICENSE: Apache 2.0
 */

Braces trim

Prohibits empty first and last lines in code blocks.

Before

void onReceive(Integer value) {

    if (value != null) {
        total += value;

    }
}
def onReceive(Integer value) {

    if (value != null) {
        total += value

    }
}
fun onReceive(value: Int?) {

    if (value != null) {
        total += value

    }
}
void onReceive(int value) {

    if (value != 0) {
        total += value;

    }
}
foo = {

    'bar',
    'baz',
    'qux',

}
function onReceive(value) {

    if (value != null) {
        total += value;

    }
}
function onReceive(value: number | null): void {

    if (value != null) {
        total += value;

    }
}

After

void onReceive(Integer value) {
    if (value != null) {
        total += value;
    }
}
def onReceive(Integer value) {
    if (value != null) {
        total += value
    }
}
fun onReceive(value: Int?) {
    if (value != null) {
        total += value
    }
}
void onReceive(int value) {
    if (value != 0) {
        total += value;
    }
}
foo = {
    'bar',
    'baz',
    'qux',
}
function onReceive(value) {
    if (value != null) {
        total += value;
    }
}
function onReceive(value: number | null): void {
    if (value != null) {
        total += value;
    }
}

Brackets trim

Prohibits empty first and last lines in collection initializers.

Before

var pond = [

    new Fish('Nemo'),
    new Fish('Dory'),
    new Fish('Marlin'),

]
Fish dory =
    pond[

        0

    ];
pond = [

    Fish('Nemo'),
    Fish('Dory'),
    Fish('Marlin'),

]
const pond = [

    new Fish('Nemo'),
    new Fish('Dory'),
    new Fish('Marlin'),

]
const pond: Fish[] = [

    new Fish('Nemo'),
    new Fish('Dory'),
    new Fish('Marlin'),

]

After

var pond = [
    new Fish('Nemo'),
    new Fish('Dory'),
    new Fish('Marlin'),
]
Fish dory =
    pond[
        0
    ];
pond = [
    Fish('Nemo'),
    Fish('Dory'),
    Fish('Marlin'),
]
const pond = [
    new Fish('Nemo'),
    new Fish('Dory'),
    new Fish('Marlin'),
]
const pond: Fish[] = [
    new Fish('Nemo'),
    new Fish('Dory'),
    new Fish('Marlin'),
]

Comment trim

Prohibits empty first and last lines in EOL comments.

Before

//
// This is a
// multiline comment
//
//
// This is a
// multiline comment
//
//
// This is a
// multiline comment
//
//
// This is a
// multiline comment
//
#
# This is a
# multiline comment
#
//
// This is a
// multiline comment
//
//
// This is a
// multiline comment
//

After

// This is a
// multiline comment
// This is a
// multiline comment
// This is a
// multiline comment
// This is a
// multiline comment
# This is a
# multiline comment
// This is a
// multiline comment
// This is a
// multiline comment

Duplicate blank line

Prohibits consecutive blank lines in the code.

Before

String message = "Hello";


System.out.println(message);
var message = 'Hello'


println(message)
val message = "Hello"


println(message)
std::string message = "Hello";


std::cout << message << std::endl;
message = 'Hello'


print(message)
const message = 'Hello';


console.log(message);
const message: string = 'Hello';


console.log(message);

Warning

PEP8 allows two blank lines between top-level functions and class definitions.

After

String message = "Hello";

System.out.println(message);
var message = 'Hello'

println(message)
val message = "Hello"

println(message)
std::string message = "Hello";

std::cout << message << std::endl;
message = 'Hello'

print(message)
const message = 'Hello';

console.log(message);
const message: string = 'Hello';

console.log(message);

Duplicate blank line in block comment

Prohibits consecutive blank lines in block comments.

Before

/**
 * This is a
 *
 *
 * very long comment
 */
/**
 * This is a
 *
 *
 * very long comment
 */
/**
 * This is a
 *
 *
 * very long comment
 */
/**
 * This is a
 *
 *
 * very long comment
 */
"""
This is a


very long comment
"""
/**
 * This is a
 *
 *
 * very long comment
 */
/**
 * This is a
 *
 *
 * very long comment
 */

After

/**
 * This is a
 *
 * very long comment
 */
/**
 * This is a
 *
 * very long comment
 */
/**
 * This is a
 *
 * very long comment
 */
/**
 * This is a
 *
 * very long comment
 */
"""
This is a

very long comment
"""
/**
 * This is a
 *
 * very long comment
 */
/**
 * This is a
 *
 * very long comment
 */

Duplicate blank line in comment

Prohibits consecutive blank lines in comments.

Before

// This is a
//
//
// very long comment
// This is a
//
//
// very long comment
// This is a
//
//
// very long comment
// This is a
//
//
// very long comment
# This is a
#
#
# very long comment
// This is a
//
//
// very long comment
// This is a
//
//
// very long comment

After

// This is a
//
// very long comment
// This is a
//
// very long comment
// This is a
//
// very long comment
// This is a
//
// very long comment
# This is a
#
# very long comment
// This is a
//
// very long comment
// This is a
//
// very long comment

Duplicate space

Prohibits consecutive spaces in the code.

Before

double tax      = 0.2;
double subtotal = bill     * tax;
double total    = subtotal + bill;
var tax      = 0.2d
var subtotal = bill     * tax
var total    = subtotal + bill
val tax      = 0.2d
val subtotal = bill     * tax
val total    = subtotal + bill
double tax      = 0.2;
double subtotal = bill     * tax;
double total    = subtotal + bill;
tax      = 0.2
subtotal = bill     * tax
total    = subtotal + bill
const tax      = 0.2;
const subtotal = bill     * tax;
const total    = subtotal + bill;
const tax: number      = 0.2;
const subtotal: number = bill     * tax;
const total: number    = subtotal + bill;

After

double tax = 0.2;
double subtotal = bill * tax;
double total = subtotal + bill;
var tax = 0.2d
var subtotal = bill * tax
var total = subtotal + bill
val tax = 0.2d
val subtotal = bill * tax
val total = subtotal + bill
double tax = 0.2;
double subtotal = bill * tax;
double total = subtotal + bill;
tax = 0.2
subtotal = bill * tax
total = subtotal + bill
const tax = 0.2;
const subtotal = bill * tax;
const total = subtotal + bill;
const tax: number = 0.2;
const subtotal: number = bill * tax;
const total: number = subtotal + bill;

Parentheses trim

Prohibits empty first and last lines in method declarations and calls.

Before

void swim(

    Fish fish,
    Pond pond
) {
    pond.release(
        fish

    );
}
def swim(

    Fish fish,
    Pond pond
) {
    pond.release(
        fish,

    )
}
fun swim(

    Fish fish,
    Pond pond,
) {
    pond.release(
        fish,

    )
}
void swim(

    Fish fish,
    Pond pond
) {
    pond.release(
        fish

    );
}
def swim(

    fish,
    pond,
):
    pond.release(
        fish,

    )
function swim(

    fish,
    pond,
) {
    pond.release(
        fish,

    );
}
function swim(

    fish: Fish,
    pond: Pond,
): void {
    pond.release(
        fish,

    );
}

After

void swim(
    Fish fish,
    Pond pond
) {
    pond.release(
        fish
    );
}
def swim(
    Fish fish,
    Pond pond
) {
    pond.release(
        fish,
    )
}
fun swim(
    fish: Fish,
    pond: Pond,
) {
    pond.release(
        fish,
    )
}
void swim(
    Fish fish,
    Pond pond
) {
    pond.release(
        fish
    );
}
def swim(
    fish,
    pond,
):
    pond.release(
        fish,
    )
function swim(
    fish,
    pond,
) {
    pond.release(
        fish,
    );
}
function swim(
    fish: Fish,
    pond: Pond,
): void {
    pond.release(
        fish,
    );
}

Tags trim

Prohibits empty first and last lines in generic type parameters.

Before

Triple<

    String,
    Integer,
    Boolean

> userAgeMarried = new Triple<>("Hank Hill", 41, true);
Triple<

    String,
    Integer,
    Boolean

> userAgeMarried = new Triple<>('Hank Hill', 41, true)
val userAgeMarried =
    new Triple<

        String,
        Integer,
        Boolean

    >('Hank Hill', 41, true)
template<

    typename T1,
    typename T2,
    typename T3

>
struct Triple {
    T1 first;
    T2 second;
    T3 third;
};
type Triple<

  T1,
  T2,
  T3,

> = {
    first: T1;
    second: T2;
    third: T3;
};

After

Triple<
    String,
    Integer,
    Boolean
> userAgeMarried = new Triple<>("Hank Hill", 41, true);
Triple<
    String,
    Integer,
    Boolean
> userAgeMarried = new Triple<>('Hank Hill', 41, true)
val userAgeMarried =
    Triple<

        String,
        Integer,
        Boolean

    >('Hank Hill', 41, true)
template<
    typename T1,
    typename T2,
    typename T3
>
struct Triple {
    T1 first;
    T2 second;
    T3 third;
};
type Triple<
  T1,
  T2,
  T3,
> = {
    first: T1;
    second: T2;
    third: T3;
};

Unnecessary blank line after colon

Prohibits first empty line in Python function and class definitions.

Before

def on_receive(value):

    if value is not None:
        total += value

After

def on_receive(value):
    if value is not None:
        total += value

Unnecessary leading blank line

The first line of a file cannot be a blank line.

Before

\n
package com.example;

void execute() {}
\n
package com.example

def execute() {}
\n
package com.example

fun execute() {}
\n
def execute():
    pass
\n
function execute() {}
\n
function execute(): void {}

After

package com.example;

void execute() {}
package com.example

def execute() {}
package com.example

fun execute() {}
def execute():
    pass
function execute() {}
function execute(): void {}

Wrapping

Assignment wrap

Assignee and the value of assignment spanning multiple lines should be separated by a newline.

Before

String message = new StringBuilder()
    .append("Hello")
    .append(" World")
    .toString();
var message = new StringBuilder()
    .append('Hello')
    .append(' World')
    .toString()
val message = buildString {
    append("Hello")
    append(" World")
}
std::string message = std::string()
    .append("Hello")
    .append(" World")
    .toString();
const message = 'Hello'
    .concat(' World')
const message: string = 'Hello'
    .concat(' World')

After

String message =
    new StringBuilder()
        .append("Hello")
        .append(" World")
        .toString();
var message =
    new StringBuilder()
        .append('Hello')
        .append(' World')
        .toString()
val message =
    buildString {
        append("Hello")
        append(" World")
    }
std::string message =
    std::string()
        .append("Hello")
        .append(" World")
        .toString();
const message: string =
    'Hello'
        .concat(' World')
const message: string =
    'Hello'
        .concat(' World')

Chain call wrap

Each method call in a chain should be aligned with the dot operator.

Before

int senderId =
    notification.getSender()
        .getId();
var senderId =
    notification.getSender()
        .getId()
val senderId =
    notification.getSender()
        .id.takeIf { it.isNotBlank() }
int senderId =
    notification.getSender()
        ->getId();
const senderId =
    notification.getSender()
        .getId();
const senderId: number =
    notification.getSender()
        .getId();

After

int senderId =
    notification
        .getSender()
        .getId();
var senderId =
    notification
        .getSender()
        .getId()
val senderId =
    notification
        .getSender()
        .id
int senderId =
    notification
        ->getSender()
        ->getId();
const senderId =
    notification
        .getSender()
        .getId();
const senderId: number =
    notification
        .getSender()
        .getId();

Elvis wrap

In a multiline statement, the elvis operator should be separated into a new line instead of trailing the statement.

Before

user.name
    .takeIf { it.isNotBlank() } ?: "Unknown"

After

user.name
    .takeIf { it.isNotBlank() }
    ?: "Unknown"

Infix call wrap

When breaking an infix function call, the operator should be placed at the end of the line.

Before

val ages =
    mapOf(
        "Alice"
            to 25,
        "Bob"
            to 30,
    )

After

val ages =
    mapOf(
        "Alice" to
            25,
        "Bob" to
            30,
    )

Lambda wrap

When breaking a multiline lambda expression, the body should be placed on a new line.

Before

int sum =
    IntStream
        .range(0, 10)
        .map(i -> i
            * 2
        ).sum();
var sum =
    IntStream
        .range(0, 10)
        .map { i -> i
            * 2
        }.sum()
const sum =
    Array
        .from({ length: 10 }, (_, i) => i)
        .map(i => i
            * 2
        ).reduce((a, b) => a + b, 0);
const sum: number =
    Array
        .from({ length: 10 }, (_, i) => i)
        .map(i => i
            * 2
        ).reduce((a, b) => a + b, 0);

After

int sum =
    IntStream
        .range(0, 10)
        .map(i ->
            i * 2
        ).sum();
var sum =
    IntStream
        .range(0, 10)
        .map { i ->
            i * 2
        }.sum()
const sum =
    Array
        .from({ length: 10 }, (_, i) => i)
        .map(i =>
            i * 2
        ).reduce((a, b) => a + b, 0);
const sum: number =
    Array
        .from({ length: 10 }, (_, i) => i)
        .map(i =>
            i * 2
        ).reduce((a, b) => a + b, 0);

Operator wrap

A line break should be placed after the operator in a binary expression.

Before

int total =
    subtotal
    + tax
    - discount;
var total =
    subtotal
    + tax
    - discount
val total =
    subtotal
    + tax
    - discount
int total =
    subtotal
    + tax
    - discount;
const total =
    subtotal
    + tax
    - discount;
const total: number =
    subtotal
    + tax
    - discount;

After

int total =
    subtotal +
    tax -
    discount;
var total =
    subtotal +
    tax -
    discount
val total =
    subtotal +
    tax -
    discount
int total =
    subtotal +
    tax -
    discount;
const total =
    subtotal +
    tax -
    discount;
const total: number =
    subtotal +
    tax -
    discount;

Parameter wrap

When breaking a multiline parameter list, each parameter should be placed on a new line.

Before

void createUser(
    String name, String email, int age
) {}
def createUser(
    String name, String email, int age
) {}
fun createUser(
    name: String, email: String, age: Int
) {}
void createUser(
    String name, String email, int age
) {}
def create_user(
    name, email, age
):
    pass
function createUser(
    name, email, age
) {}
function createUser(
    name: string, email: string, age: number
): void {}

After

void createUser(
    String name,
    String email,
    int age
) {}
def createUser(
    String name,
    String email,
    int age,
) {}
fun createUser(
    name: String,
    email: String,
    age: Int,
) {}
void createUser(
    String name,
    String email,
    int age
) {}
def create_user(
    name,
    email,
    age,
):
    pass
function createUser(
    name,
    email,
    age,
) {}
function createUser(
    name: string,
    email: string,
    age: number,
): void {}

Statement wrap

Compound statements are not allowed.

Before

int x = 0; int y = 0;
var x = 0; var y = 0
val x = 0; val y = 0
x = 0; y = 0
const x = 0; const y = 0;
const x: number = 0; const y: number = 0;

After

int x = 0;
int y = 0;
var x = 0
var y = 0
val x = 0
val y = 0
x = 0
y = 0
const x = 0;
const y = 0;
const x: number = 0;
const y: number = 0;