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.
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.
For an introduction to natural naming, see A guide to natual naming (by Daniel Keller, from the ACM Digital Library).
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 |
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:
sort(items: list)
: Modify an existing array so that the items in it are sorted.copy_file(source_path: Path, target_path: Path)
: Create a copy of the file named source_path
as a new file named target_path
.Examples:
sorted(items: list) -> list
: Return a copy of items
where the entries are sorted. Leave the original items
passed as parameter as they where.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.") ...
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".
The ordering for globals in the source code is:
DEFAULT_ENCODING = "utf-8"
_COLOR_REGEX = re.compile(r"^(#?)(?P<code>[\da-fA-F]{6})$")
item_cache = {}`
_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"