Code Style Guidelines

Goals

  • Uniformity in code
    • If you look at code and can tell who wrote it, that’s not good
  • Rules should be automatable
  • Code should be easy to read / understand

Rules

Commenting (uniformity)

Function documentation (jsdoc/docstrings)

/**
 * Given an option and its parent group, update the filter state based on the `isEnabled` prop
 *
 * @param  {Object}  group
 * @param  {Object}  option
 * @param  {Boolean} isEnabled
 */
function selectFilter({ group, option, isEnabled }) {
  return {
    type: group.value === 'text' ? SET_TEXT_FILTER : SET_FILTER,
    group,
    option,
    isEnabled,
  };
}

Rule: Use full width for wrapping comments (80-100 chars)

Rule: JSDoc: Param descriptions only if needed

/**
 * Given an option and its parent group, update the filter state based on the `isEnabled` prop
 */
function selectFilter({
  group: Object,
  option: Object,
  isEnabled: Boolean,
}) {
  return {
    type: group.value === 'text' ? SET_TEXT_FILTER : SET_FILTER,
    group,
    option,
    isEnabled,
  };
}

Consider: type annotation for new projects (Flow or TypeScript)

String formatting (uniformity)

  • Python
    • Use format strings: f”{2 + 2}”
    • Or .format() if in Python < 3.6
  • JS
    • Use template strings

Naming (uniformity)

  • Boolean fields: is_foo and has_bar
  • Python
    • snake_case variables and method names
    • UpperCamel for classes
  • JS
    • camelCase variables and method names

Wrapping

Long parameter lists:

function foo(a, b, c, d, e, f, g, h, i, j) { ... }

becomes

function foo(
  a,
  b,
  c,
  d,
  ...
) {
  ...
}

Rule: All on one line, or one parameter per line

Complex if statements

if (!this.normandy.testing && (
  await this.heartbeatShownRecently() ||
  await this.surveyHasShown()
)) {
  return;
}

becomes

const hasShown = await this.heartbeatShownRecently() || await this.surveyHasShown();
if (!this.normandy.test && hasShown) { ... }

Rule: No extra parens inside if conditions

Placement of operators

Bad

const hasExecuted = await this.heartbeatShownRecently() ||
  await this.surveyHasShown();

Good

const hasExecuted = await this.heartbeatShownRecently()
  || await this.surveyHasShown();

Rule: put boolean operators on the next line

Really long if statements

Rule: indent on the next line

if (
    thisIsAReallyLongName
    && thisIsAReallyLongNameAlso
    && thisIsAReallyLongNameAsWell
) {
    console.log('ok');
}