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.
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_pathas a new file named
sorted(items: list) -> list: Return a copy of
itemswhere the entries are sorted. Leave the original
itemspassed 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.
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".