title_wip

[Edit this page](https://github.com/ClickHouse/ClickHouse/tree/master/docs/en/development/style.md)

## General recommendations[​](#general-recommendations "Direct link to General recommendations")

The following are recommendations, not requirements.
If you are editing code, it makes sense to follow the formatting of the existing code.
Code style is needed for consistency. Consistency makes it easier to read the code, and it also makes it easier to search the code.
Many of the rules do not have logical reasons; they are dictated by established practices.

## Formatting[​](#formatting "Direct link to Formatting")

**1.** Most of the formatting is done automatically by `clang-format`.

**2.** Indents is 4 spaces. Configure your development environment so that a tab adds four spaces.

**3.** Opening and closing curly brackets must be on a separate line.

```
inline void readBoolText(bool & x, ReadBuffer & buf)
{
    char tmp = '0';
    readChar(tmp, buf);
    x = tmp != '0';
}
```

**4.** If the entire function body is a single `statement`, it can be placed on a single line. Place spaces around curly braces (besides the space at the end of the line).

```
inline size_t mask() const                { return buf_size() - 1; }
inline size_t place(HashValue x) const    { return x & mask(); }
```

**5.** For functions. Don't put spaces around brackets.

```
void reinsert(const Value & x)
```

```
memcpy(&buf[place_value], &x, sizeof(x));
```

**6.** In `if`, `for`, `while` and other expressions, a space is inserted in front of the opening bracket (as opposed to function calls).

```
for (size_t i = 0; i < rows; i += storage.index_granularity)
```

**7.** Add spaces around binary operators (`+`, `-`, `*`, `/`, `%`, ...) and the ternary operator `?:`.

```
UInt16 year = (s[0] - '0') * 1000 + (s[1] - '0') * 100 + (s[2] - '0') * 10 + (s[3] - '0');
UInt8 month = (s[5] - '0') * 10 + (s[6] - '0');
UInt8 day = (s[8] - '0') * 10 + (s[9] - '0');
```

**8.** If a line feed is entered, put the operator on a new line and increase the indent before it.

```
if (elapsed_ns)
    message << " ("
        << rows_read_on_server * 1000000000 / elapsed_ns << " rows/s., "
        << bytes_read_on_server * 1000.0 / elapsed_ns << " MB/s.) ";
```

**9.** You can use spaces for alignment within a line, if desired.

```
dst.ClickLogID         = click.LogID;
dst.ClickEventID       = click.EventID;
dst.ClickGoodEvent     = click.GoodEvent;
```

**10.** Don't use spaces around the operators `.`, `->`.

If necessary, the operator can be wrapped to the next line. In this case, the offset in front of it is increased.

**11.** Do not use a space to separate unary operators (`--`, `++`, `*`, `&`, ...) from the argument.

**12.** Put a space after a comma, but not before it. The same rule goes for a semicolon inside a `for` expression.

**13.** Do not use spaces to separate the `[]` operator.

**14.** In a `template <...>` expression, use a space between `template` and `<`; no spaces after `<` or before `>`.

```
template <typename TKey, typename TValue>
struct AggregatedStatElement
{}
```

**15.** In classes and structures, write `public`, `private`, and `protected` on the same level as `class/struct`, and indent the rest of the code.

```
template <typename T>
class MultiVersion
{
public:
    /// Version of object for usage. shared_ptr manage lifetime of version.
    using Version = std::shared_ptr<const T>;
    ...
}
```

**16.** If the same `namespace` is used for the entire file, and there isn't anything else significant, an offset is not necessary inside `namespace`.

**17.** If the block for an `if`, `for`, `while`, or other expression consists of a single `statement`, the curly brackets are optional. Place the `statement` on a separate line, instead. This rule is also valid for nested `if`, `for`, `while`, ...

But if the inner `statement` contains curly brackets or `else`, the external block should be written in curly brackets.

```
/// Finish write.
for (auto & stream : streams)
    stream.second->finalize();
```

**18.** There shouldn't be any spaces at the ends of lines.

**19.** Source files are UTF-8 encoded.

**20.** Non-ASCII characters can be used in string literals.

```
<< ", " << (timer.elapsed() / chunks_stats.hits) << " μsec/hit.";
```

**21.** Do not write multiple expressions in a single line.

**22.** Group sections of code inside functions and separate them with no more than one empty line.

**23.** Separate functions, classes, and so on with one or two empty lines.

**24.** `A const` (related to a value) must be written before the type name.

```
//correct
const char * pos
const std::string & s
//incorrect
char const * pos
```

**25.** When declaring a pointer or reference, the `*` and `&` symbols should be separated by spaces on both sides.

```
//correct
const char * pos
//incorrect
const char* pos
const char *pos
```

**26.** When using template types, alias them with the `using` keyword (except in the simplest cases).

In other words, the template parameters are specified only in `using` and aren't repeated in the code.

`using` can be declared locally, such as inside a function.

```
//correct
using FileStreams = std::map<std::string, std::shared_ptr<Stream>>;
FileStreams streams;
//incorrect
std::map<std::string, std::shared_ptr<Stream>> streams;
```

**27.** Do not declare several variables of different types in one statement.

```
//incorrect
int x, *y;
```

**28.** Do not use C-style casts.

```
//incorrect
std::cerr << (int)c <<; std::endl;
//correct
std::cerr << static_cast<int>(c) << std::endl;
```

**29.** In classes and structs, group members and functions separately inside each visibility scope.

**30.** For small classes and structs, it is not necessary to separate the method declaration from the implementation.

The same is true for small methods in any classes or structs.

For template classes and structs, do not separate the method declarations from the implementation (because otherwise they must be defined in the same translation unit).

**31.** You can wrap lines at 140 characters, instead of 80.

**32.** Always use the prefix increment/decrement operators if postfix is not required.

```
for (Names::const_iterator it = column_names.begin(); it != column_names.end(); ++it)
```

## Comments[​](#comments "Direct link to Comments")

**1.** Be sure to add comments for all non-trivial parts of code.

This is very important. Writing the comment might help you realize that the code isn't necessary, or that it is designed wrong.

```
/** Part of piece of memory, that can be used.
  * For example, if internal_buffer is 1MB, and there was only 10 bytes loaded to buffer from file for reading,
  * then working_buffer will have size of only 10 bytes
  * (working_buffer.end() will point to position right after those 10 bytes available for read).
  */
```

**2.** Comments can be as detailed as necessary.

**3.** Place comments before the code they describe. In rare cases, comments can come after the code, on the same line.

```
/** Parses and executes the query.
*/
void executeQuery(
    ReadBuffer & istr, /// Where to read the query from (and data for INSERT, if applicable)
    WriteBuffer & ostr, /// Where to write the result
    Context & context, /// DB, tables, data types, engines, functions, aggregate functions...
    BlockInputStreamPtr & query_plan, /// Here could be written the description on how query was executed
    QueryProcessingStage::Enum stage = QueryProcessingStage::Complete /// Up to which stage process the SELECT query
    )
```

**4.** Comments should be written in English only.

**5.** If you are writing a library, include detailed comments explaining it in the main header file.

**6.** Do not add comments that do not provide additional information. In particular, do not leave empty comments like this:

```
/*
* Procedure Name:
* Original procedure name:
* Author:
* Date of creation:
* Dates of modification:
* Modification authors:
* Original file name:
* Purpose:
* Intent:
* Designation:
* Classes used:
* Constants:
* Local variables:
* Parameters:
* Date of creation:
* Purpose:
*/
```