2.7. Comments and Documentation

2.7.1. Example 1: Redundant comments

Hat tip to Arthur Turrell.

2.7.2. Example 2: Excessive comments

# Elasticity = Percent Change in Quantity / Percent Change in Price
# Elasticity = 0.4 / 0.2 = 2
# See Shapiro (2005), The Economics of Potato Chips,
# Harvard University Mimeo, Table 2A.
compute_welfare_loss(elasticity=2)

Suppose you later change this file and you change elasticity=2. It will be tempting to forget to change the comment associated with it, or explain why.

So using comments makes it possible that your code becomes internally inconsistent; almost by definition, programmers have an interesting tendency towards a (typically smart) form of laziness!

2.7.3. Example 3: Self-documenting code

We can write the exact same code in a way that prevents that possible problem. Look at this version, which still documents the code just as well because it is self-documenting:

# See Shapiro (2005), The Economics of Potato Chips,
# Harvard University Mimeo, Table 2A.
percent_change_in_quantity = -0.4
percent_change_in_price = 0.2
elasticity = percent_change_in_quantity/percent_change_in_price

2.7.4. How to write self-documenting code

Making code easy to read and maintain is a guiding principle for experienced coders because we’ve all wasted so much time fixing code or simply trying to use code we wrote a few years ago. Self-documenting code makes this easy and saves a lot of headaches. That is why the aim for self-documentation underlies the logic behind the Good Data page, the Directory page, how we name files and functions, etc.

A few more tips to help write more readable code:

  • Use the naming of variables and the structure of the code to help guide a reader through your operations

  • x and y are usually (but not always!) bad variable names because they are uninformative

  • Calling a dataframe df should be avoided as well

  • Documentation is sometimes necessary and unavoidable. (Citing “The Economics of Potato Chips” in the example above is smart.)

  • Documentation can clarify that, “Yes, I did mean to do this on purpose!”