Skip to content

Instantly share code, notes, and snippets.

@bergwerf
Last active November 9, 2016 09:26
Show Gist options
  • Save bergwerf/aaed9c08ab353b89ab7e to your computer and use it in GitHub Desktop.
Save bergwerf/aaed9c08ab353b89ab7e to your computer and use it in GitHub Desktop.
My personal coding style preferences!

A style guide

This used to be my preferred style some years ago. Nowadays I'm less opiniated and I try to follow standard conventions and use standard formatters, such as the excellent dartfmt for Dart.

Miscellaneous

This section contains the general code formatting style conventions. The exact formatting may differ per language.

Indentation 4 spaces
Line length 80 characters is the absolute limit
Carriage return Unix-style ("\n") rather than Windows/DOS ("\r\n")
Semicolons Use semicolons to separate statements
Boolean comparisons Use (x) and (!x) instead of x == true and x == false.

Color notation

When choosing a color notation, you should use the following rules.

  1. Use named colors, such as red, when possible to enhance readability.
  2. Use hex values for shades of grey. Use the shorthand notation #rgb when possible.
  3. Use opacity instead of rgba or hsla when possible
  4. Use HSL for colors. RGB is acceptable for shades of red, green or blue.

Double and single quotes

Double and single quotes can often both be used to enclose strings. Some languages restrict their usage, many don't. If the language does not restrict their usage, the following rules must be applied to decide if you should use single or double quotes.

  1. Use double quotes if the string is read by end users. When in doubt, ask yourself this question: Would this piece of text be translated into another human language?
  2. Use double quotes if the string contains more single quotes than double quotes.
  3. Use single quotes in all other cases.

The example below illustrates these rules.

a = "Hello Human!"             # This is supposed to be read by a human
                               # and is also supposed to be translated.
b = "don't use ', use \""      # There are more single quotes.
c = 'index.html'               # This would never be translated.
d = '<img src="awesome.png">'  # Use single quotes to enclose double quotes.

Indentation

MolView uses the Allman indent style where possible because this indent style helps to distinguish blocks of code more easily. This means braces, brackets or parentheses are placed on their own line in most cases. However, there are a few exceptions.

  1. Assignments: the first brace, bracket or parenthesis is placed on the same line as the assignment operator.
  2. Function expressions: the first brace of a function expression must be placed on the same line as the function keyword.
  3. Small homogeneous sets: if a homogeneous set, such as an array, is small enough to fit on the same line, the opening and closing characters are also on this same line.

The example below illustrates these exceptions.

var oneToFive   = [ 1, 2, 3, 4, 5 ];  // small homogeneous set
var oneToFifty  = [                   // big homogeneous set
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
    22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50
];

var object = {                        // first brace on the same line
    "country":    "Netherlands",
    "continent":  "Europe",
    "planet":     "Earth"
};

var print = function(msg) {           // function expression
    console.log(msg);
};

function log(msg)                     // function declaration
{
    if (msg != "")
    {
        console.log(msg);
    }
};

When to use line breaks

Apart from using line breaks for proper indentation and to honor the 80 character line limit, there are a few rules for explicitly using line breaks in certain situations.

  1. At the end of each source file: source files should always end with a line break
  2. After non-homogeneous elements in a set: a set containing non-homogeneous elements, such as a tuple, should use one line for each element. This way it is easier to distinguish individual elements. This also leaves space for commenting the elements like in the example below. However, this is not compulsory In some cases it makes more sense to put a non-homogeneous set on a single line.
var json = {
    "array": [ 0, 1, 2, 3, 4, 5 ]  // homogeneous set
    "object": {
        "homogeneous": false,      // This object is not homogeneous.
        "key": "value"             // The value of "key" is "value".
    },
    // This style is also possible.
    "sameObject": { "homogeneous": false, "key": "value" }
};

When to use spaces

Use one space whenever spaces can be used except in the following cases:

  1. Before a comma, colon or semicolon
  2. After an opening parenthesis
  3. Before a closing parenthesis
  4. Around the lt and before the gt character used for a template class.
  5. Around the array length number in brackets
  6. Between a function name and the opening parenthesis
  7. Between a type or value label and a pointer, array or set character (Go uses this: array := []int{ 1, 2, 3})
int numbers[3] = { 1, 2, 3 };
int* answer;
*answer = 6;

if (addition(numbers) == *answer)
{
    printf("I can perform additions!\n");
}
else
{
    for (int i = 0; i < 1000; i++)
    {
        printf("I failed to perform one of the simplest numerical tasks!\n");
    }
}

Vertical alignment using spaces

It is recommended to vertically align code using spaces. When aligning code, make sure the smallest gap is exactly two spaces wide.

Names

This section contains the naming conventions that should be honored across the MolView code.

Class and Enum names UpperCamelCase
Functions and methods lowerCamelCase
Private methods _lowerCamelCase
Variables lowerCamelCase
Private variables _lowerCamelCase
Constant values UPPER_SNAKE_CASE
Folder and file names spinal-case or nodelimitercase

Abbreviations

Unless an abbreviation is more common than the unabbreviated term, don’t abbreviate. If you do abbreviate, capitalize acronyms and abbreviations over two letters like words.

  • Right: HttpRequest, XmlFile, IOStream, Id
  • Wrong: HTTPRequest, XMLFile, IoStream, ID

Preferred case

Prefer lowercase over uppercase (for color codes, XML tags, etc.). Use uppercase for abbreviations if the uppercase variant is more common than the lowercase variant like for XML or POSIX.

Comments

This section contains the formatting and writing style conventions for commenting code.

  • Punctuation: Use full punctuation everywhere.
  • Imperative: Use the imperative when possible with caps and periods.
  • Markup: Use Markdown.

Single line comments

Vertically align (using spaces) single line comments as shown below. Use at least two spaces padding at the left side of the comment and add one space after the beginning of the comment (usually // or #). If the comment does not fit on one line, use one of the two styles shown below.

double e   = 2.7183;  // Euler's number
double pi  = 3.1416;  // C/D
double phi = 1.6180;  /* the golden ratio, named
                         after the Greek sculptor Phidias */
double tau = 6.2832;  // tau > pi!
                      // no really, pi is wrong...

Block comments

The block comment format for the most common comment styles is shown below. You should separate code and block comments with a blank line. However, you don't have to add a blank line before braces and functions, methods or values it is associated with.

/*
Heading
=======
The quick brown fox jumps over a lazy dog.
*/
# Heading
# =======
# The quick brown fox jumps over a lazy dog.

Comment out code

For commenting out a single line of code you can use the single line comment style. However, you should not put a space between the start of the comment and the code like in this example:

var value = "key";
//var greeting = "hello";

To comment out a block of code, you should use the same rules as described for block comments. However, you should again leave no space between the comment characters and the code you are commenting out like shown below.

/*var a = "a";
var b = "b";
var c = "c";*/
#var a = "a";
#var b = "b";
#var c = "c";

Documentation comments

Documentation comments should be used for the documentation of classes, class members enums, namespaces and functions. The documentation comment format for the most common comment styles is shown below. The blank line rules for block comments also apply to documentation comments.

/**
 * Heading
 * =======
 * The quick brown fox jumps over a lazy dog.
 */
"""
Heading
=======
The quick brown fox jumps over a lazy dog.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment