Reading Notes: 'The Art of Readable Code'

Key takeaways from 'The Art of Readable Code' covering naming conventions, avoiding misleading names, code aesthetics, and effective commenting.

The Art of Readable Code: Simple and Practical Techniques for Writing Better Code provides concrete guidelines for writing code that is easy to read and understand. Below is a summary of its key points.

1. Pack Information into Names

Names, starting with variables, should clearly convey their role and content.

  • Use specific words instead of generic ones:

    Generic WordAlternatives
    getfetch, download, retrieve
    sizeheight, numNodes, memoryBytes
    stopkill, pause, halt
    senddeliver, dispatch, announce, distribute, route
    findsearch, extract, locate, recover
    startlaunch, create, begin, open
    makecreate, setUp, build, generate, compose, add, new
  • Use concrete names instead of abstract ones:

    • tmp should only be used for variables with very short lifetimes where temporary storage is the most important aspect.
    • For iterator variables, instead of using i, j, k, use descriptive names like club_idx, member_idx, user_idx.
    • Use more direct and explicit expressions:
      // Bad
      ServerCanStart
      // Good
      CanListenOnPort
      
  • Add information with suffixes and prefixes:

    • delay -> delay_secs (unit)
    • size -> size_mb (unit)
    • limit -> max_kbp (limit)
    • angle -> degree_cw (unit and direction)
    • html -> html_utf8 (encoding)
  • Choose appropriate name length:

    • Shorten overly long names:
      • FormatString -> FormatStr
      • ConvertToString -> ToString
    • Lengthen overly short names.
  • Convey information through name formatting:

    • Embed meaning in naming conventions such as capitalization and underscores (e.g., use all uppercase with underscores for constants).

2. Use Names That Can’t Be Misunderstood

Choose names carefully so readers won’t misinterpret them.

  • Watch out for ambiguous words:

    • filter -> select (include), exclude (exclude)
    • clip -> remove (delete), truncate (cut short)
  • Indicate limits:

    • Use max or limit for maximum values, and min for minimum values.
    • Examples: max_users, min_length
  • Indicate ranges:

    • Use first and last for inclusive ranges.
    • Use begin and end for exclusive ranges.
  • Boolean variable names:

    • Prefix boolean variables with is_, has_, can_, should_ to make true/false meaning clear.
    • Examples: is_valid, has_permission, can_read, should_process
  • Match user expectations:

    • get methods are generally expected to be lightweight accessors with no side effects. For expensive computations or operations with side effects, use verbs like compute or calculate.
    • size methods are expected to return in $O(1)$ time. If computation is involved, use names like count or calculate_size.

3. Aesthetics (Code Formatting and Layout)

Code appearance significantly impacts readability.

  • Use layouts consistent with patterns readers are familiar with: Follow coding conventions of the project or language.
  • Make similar code look similar: Format structurally similar code blocks in the same way.
  • Group related code into blocks: Separate logically related lines with blank lines.
  • Use consistent line breaks: Standardize line break rules to reduce visual noise.
  • Align vertical lines: Align assignment operators or arguments vertically to make code structure easier to grasp.
    details  = request.POST.get('detail')
    location = request.POST.get('location')
    phone    = request.POST.get('phone')
    
  • Use meaningful ordering: Arrange variable declarations or function arguments in a logical order.
  • Group declarations into blocks: Gather related variable declarations in one place, such as the beginning of a code block.

4. Comments

Write comments to supplement “why” and “what” that code alone cannot convey.

  • Don’t comment on things immediately obvious from code: e.g., i = 0; // Initialize i to 0 is unnecessary.
  • Comment on constants: Use named constants instead of magic numbers, and supplement them with comments explaining their meaning.
  • Avoid pronouns: Avoid “it” or “this” and use specific nouns instead.
  • Describe function behavior precisely: Concisely and accurately describe the function’s purpose, parameters, return values, side effects, and exceptions.
  • Use inline comments for unclear arguments: Add comments at the call site when argument meanings are not obvious.

References

  • Dustin Boswell, Trevor Foucher, The Art of Readable Code: Simple and Practical Techniques for Writing Better Code, O’Reilly Media (2012)