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 Word Alternatives getfetch,download,retrievesizeheight,numNodes,memoryBytesstopkill,pause,haltsenddeliver,dispatch,announce,distribute,routefindsearch,extract,locate,recoverstartlaunch,create,begin,openmakecreate,setUp,build,generate,compose,add,newUse concrete names instead of abstract ones:
tmpshould 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 likeclub_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->FormatStrConvertToString->ToString
- Lengthen overly short names.
- Shorten overly long 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
maxorlimitfor maximum values, andminfor minimum values. - Examples:
max_users,min_length
- Use
Indicate ranges:
- Use
firstandlastfor inclusive ranges. - Use
beginandendfor exclusive ranges.
- Use
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
- Prefix boolean variables with
Match user expectations:
getmethods are generally expected to be lightweight accessors with no side effects. For expensive computations or operations with side effects, use verbs likecomputeorcalculate.sizemethods are expected to return in $O(1)$ time. If computation is involved, use names likecountorcalculate_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 0is 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)