General coding guidelines

This article provides guidelines for naming source code items like variables, function and classes in a way that makes the code easy to understand and maintain.

Introduction

These guidelines are independent of the programming language used, and may be overruled by language specific guidelines. Regardless, all of my language specific guidelines refer to this document as basis.

I use these guidelines in my own projects unless there are already other, already existing guidelines to adhere to. For example, when an open source project already has its own CONTRIBUTING or a company has established existing standards.

The target audience are developers contributing to one of my projects, be it open source or commercial. It can also be of interest for people who are looking for a basis for their own guidelines.

This document is distributed under the CC BY 4.0 license.

Use natural naming

For an introduction to natural naming, see A guide to natual naming (by Daniel Keller, from the ACM Digital Library).

Avoid abbreviations

Avoid abbreviations unless you can save at least 4 letters. Example for popular abbreviations that could be rephrased better:

| Instead of... | meaning...  | better use... |
|---------------|-------------|---------------|
| dir           | directory   | folder        |
| dst           | destination | target        |
| src           | source      | source        |

Name procedures after what they do

Procedures perform an action that changes the state of the software.

Their names should start with a verb and optionall more terms specifying in greater detail what they act on.

Examples:

Name functions after their result

Examples:

If a function cannot deliver what the name promises, fail

If the function encounters an error while attempting to deliver the result its name promises, make it fail using the mechanisms the programming language offers for that such as exception handling.

Example:

import os


def do_the_foo():
    foo = os.environ.get("FOO")
    if foo is None:
        raise FooError("Cannot do the foo: environment variable FOO must be set.")
    ...

Limit complexity

Split up long functions into multiple sub-functions or a class with multiple methods.

This guideline deliberately does not include an exact definition of "long". For more details on this topic, refer to the book "Clean code", chapter 3, "Functions".

Ordering of globals

The ordering for globals in the source code is:

  1. Public constants:
    DEFAULT_ENCODING = "utf-8"
    
  2. Private constants:
    _COLOR_REGEX = re.compile(r"^(#?)(?P<code>[\da-fA-F]{6})$")
    
  3. Public globals:
    item_cache = {}`
    
  4. Private globals
    _log = logging.getLogger(__name__)
    

Exception: When dependencies are otherwise, e.g. public global depend on private global. For example:

_HELLO = "hello"
HELLO_WORLD = _HELLO + " world"