Coding Rules

Rules for writing robust, maintainable code

Rule 1: The termination condition of a loop should be easy to reason about

Infinite loops can have harmful consequences, such as blocking the browser tab, making a server unresponsive or consuming a huge amount of resources.

When writing a loop, make sure that it's obvious the loop terminates.

Rule 2: Don't use sentinel values if your language has a better alternative

A sentinel value is a value such as -1 or the empty string, that has a special meaning in the context of a program.

Sentinel values are undesirable because:

  • It isn't obvious that a type contains a sentinel value, which may result in new code not handling the sentinel value without getting a compiler error or looking obviously wrong.

  • Mistakes or future changes may result in sentinel values colliding with real values.

A better option is to use an adequate composite type such as a union type.

Rule 3: Don't use unnecessary conditionals (if, switch...)

When a piece of code contains an if condition, the code can take 2 paths. If the piece of code contains two nested if conditions, the code can take 4. If there are three the code can take 8 paths.

Each of these paths can hide a bug. The fewer conditionals there are, the fewer edge cases there are, and the more likely it is to come across the bugs when testing.

Rule 4: When you have to write non-straightforward code, explain why

It's usually better to write code in the simplest way possible. However, you might have to write code that looks unnecessarily complicated, for example to improve performance or work around problems in your environment.

If the developers who read your code don't understand why it is written the way it is, they may rewrite it the straightforward way, potentially causing bugs, performance regressions or other problems.

You can explain why your code is written the way it is in comments, commit messages, or, even better, unit tests that test the behavior that is unique to your code.