Skip to content

Code Guide

Ivan Rudik edited this page May 7, 2019 · 10 revisions

The primary goal of your coding style should be clarity. We want other people and your future self to be able to easily understand what you wrote.

LJ Ristovska wrote a nice language-agnostic programming guide.

Language-specific style

General naming convention

Variables

  • Variable names should be lowercase:
    • πŸ†— county_fips
    • ❌ County_FIPS, CountyFIPS, CountyFips, countyFIPS
  • Variable names should be descriptive:
    • πŸ†— state_fips, gas_flare_rate
    • ❌ sfps, gf_rate
  • Variable names should be underscore separated unless they are short and it is clear:
    • πŸ†— unemployment_rate_over_65, aqilevel, aqi_level
    • ❌ unemploymentrateover65
  • Prefer clarity to brevity
    • πŸ†— state_fips
    • ❌ s_fips
  • Prefer specificity to generality
    • πŸ†— nightlights_luminosity
    • ❌ nightlights
  • Be consistent
    • πŸ†— county_fips, state_fips
    • ❌ county_fips, fips_state

Functions/programs (Stata name for a function)

  • Function and program names should be verbs describing what they do
    • πŸ†— clean_birds
    • ❌ bird_cleaning, bird_cleaner
  • Function names should be lowercase:
    • πŸ†— clean_birds_data
    • ❌ CleanBirdsData, Clean_Birds_Data, cleanBirdsData
  • Function names should be underscore separated unless they are short and it is clear:
    • πŸ†— analyze_nightlights_birds, cleanbirds
    • ❌ analyze_nightlights_birds
  • Prefer clarity to brevity
    • πŸ†— clean_birds
    • ❌ cln_brds
  • Prefer specificity to generality
    • πŸ†— analyze_nightlights_birds
    • ❌ analyze_data
  • Be consistent
    • πŸ†— clean_nightlights_data, clean_birds_data
    • ❌ clean_data_birds, clean_nightlights_data

Spacing

  • Use one space before and after a single binary operator or a comparator.

    • πŸ†— this + that, this | that, a >= 0
    • ❌ this +that, this|that, a>=0
    • Spacing around ^, /, or * is optional.
  • Use a space after a comma

    • πŸ†— run_regressions(data, fixed_effects)
    • ❌ run_regressions(data,fixed_effects)
  • Do not use a space after a unary operator or % when used to force a type.

    • πŸ†— negative_id = -id
    • ❌ negative_id = - id
  • If you are going to align vertically, prefer to align on the =.

  • If the left-hand-side name lengths vary greatly in subgroups, align subgroups on the =.

  • Prefer to split a long line after =, ,, ||, &&. or (.