The Art of Readable Code

Book description

As programmers, we’ve all seen source code that’s so ugly and buggy it makes our brain ache. Over the past five years, authors Dustin Boswell and Trevor Foucher have analyzed hundreds of examples of "bad code" (much of it their own) to determine why they’re bad and how they could be improved. Their conclusion? You need to write code that minimizes the time it would take someone else to understand it—even if that someone else is you.

This book focuses on basic principles and practical techniques you can apply every time you write code. Using easy-to-digest code examples from different languages, each chapter dives into a different aspect of coding, and demonstrates how you can make your code easy to understand.

  • Simplify naming, commenting, and formatting with tips that apply to every line of code
  • Refine your program’s loops, logic, and variables to reduce complexity and confusion
  • Attack problems at the function level, such as reorganizing blocks of code to do one task at a time
  • Write effective test code that is thorough and concise—as well as readable

"Being aware of how the code you create affects those who look at it later is an important part of developing software. The authors did a great job in taking you through the different aspects of this challenge, explaining the details with instructive examples."

—Michael Hunger, passionate Software Developer

Publisher resources

View/Submit Errata

Table of contents

  1. The Art of Readable Code
  2. A Note Regarding Supplemental Files
  3. Preface
    1. What This Book Is About
    2. How to Read This Book
    3. Using Code Examples
    4. Safari® Books Online
    5. How to Contact Us
    6. Acknowledgments
  4. 1. Code Should Be Easy to Understand
    1. What Makes Code “Better”?
    2. The Fundamental Theorem of Readability
    3. Is Smaller Always Better?
    4. Does Time-Till-Understanding Conflict with Other Goals?
    5. The Hard Part
  5. I. Surface-Level Improvements
    1. 2. Packing Information into Names
      1. Choose Specific Words
        1. Finding More “Colorful” Words
      2. Avoid Generic Names Like tmp and retval
        1. tmp
        2. Loop Iterators
        3. The Verdict on Generic Names
      3. Prefer Concrete Names over Abstract Names
        1. Example: DISALLOW_EVIL_CONSTRUCTORS
        2. Example: --run_locally
      4. Attaching Extra Information to a Name
        1. Values with Units
        2. Encoding Other Important Attributes
      5. How Long Should a Name Be?
        1. Shorter Names Are Okay for Shorter Scope
        2. Typing Long Names—Not a Problem Anymore
        3. Acronyms and Abbreviations
        4. Throwing Out Unneeded Words
      6. Use Name Formatting to Convey Meaning
        1. Other Formatting Conventions
      7. Summary
    2. 3. Names That Can’t Be Misconstrued
      1. Example: Filter()
      2. Example: Clip(text, length)
      3. Prefer min and max for (Inclusive) Limits
      4. Prefer first and last for Inclusive Ranges
      5. Prefer begin and end for Inclusive/Exclusive Ranges
      6. Naming Booleans
      7. Matching Expectations of Users
        1. Example: get*()
        2. Example: list::size()
      8. Example: Evaluating Multiple Name Candidates
      9. Summary
    3. 4. Aesthetics
      1. Why Do Aesthetics Matter?
      2. Rearrange Line Breaks to Be Consistent and Compact
      3. Use Methods to Clean Up Irregularity
      4. Use Column Alignment When Helpful
        1. Should You Use Column Alignment?
      5. Pick a Meaningful Order, and Use It Consistently
      6. Organize Declarations into Blocks
      7. Break Code into “Paragraphs”
      8. Personal Style versus Consistency
      9. Summary
    4. 5. Knowing What to Comment
      1. What NOT to Comment
        1. Don’t Comment Just for the Sake of Commenting
        2. Don’t Comment Bad Names—Fix the Names Instead
      2. Recording Your Thoughts
        1. Include “Director Commentary”
        2. Comment the Flaws in Your Code
        3. Comment on Your Constants
      3. Put Yourself in the Reader’s Shoes
        1. Anticipating Likely Questions
        2. Advertising Likely Pitfalls
        3. “Big Picture” Comments
        4. Summary Comments
      4. Final Thoughts—Getting Over Writer’s Block
      5. Summary
    5. 6. Making Comments Precise and Compact
      1. Keep Comments Compact
      2. Avoid Ambiguous Pronouns
      3. Polish Sloppy Sentences
      4. Describe Function Behavior Precisely
      5. Use Input/Output Examples That Illustrate Corner Cases
      6. State the Intent of Your Code
      7. “Named Function Parameter” Comments
      8. Use Information-Dense Words
      9. Summary
  6. II. Simplifying Loops and Logic
    1. 7. Making Control Flow Easy to Read
      1. The Order of Arguments in Conditionals
      2. The Order of if/else Blocks
      3. The ?: Conditional Expression (a.k.a. “Ternary Operator”)
      4. Avoid do/while Loops
      5. Returning Early from a Function
      6. The Infamous goto
      7. Minimize Nesting
        1. How Nesting Accumulates
        2. Removing Nesting by Returning Early
        3. Removing Nesting Inside Loops
      8. Can You Follow the Flow of Execution?
      9. Summary
    2. 8. Breaking Down Giant Expressions
      1. Explaining Variables
      2. Summary Variables
      3. Using De Morgan’s Laws
      4. Abusing Short-Circuit Logic
      5. Example: Wrestling with Complicated Logic
        1. Finding a More Elegant Approach
      6. Breaking Down Giant Statements
      7. Another Creative Way to Simplify Expressions
      8. Summary
    3. 9. Variables and Readability
      1. Eliminating Variables
        1. Useless Temporary Variables
        2. Eliminating Intermediate Results
        3. Eliminating Control Flow Variables
      2. Shrink the Scope of Your Variables
        1. if Statement Scope in C++
        2. Creating “Private” Variables in JavaScript
        3. JavaScript Global Scope
        4. No Nested Scope in Python and JavaScript
        5. Moving Definitions Down
      3. Prefer Write-Once Variables
      4. A Final Example
      5. Summary
  7. III. Reorganizing Your Code
    1. 10. Extracting Unrelated Subproblems
      1. Introductory Example: findClosestLocation()
      2. Pure Utility Code
      3. Other General-Purpose Code
        1. Unexpected Benefits
      4. Create a Lot of General-Purpose Code
      5. Project-Specific Functionality
      6. Simplifying an Existing Interface
      7. Reshaping an Interface to Your Needs
      8. Taking Things Too Far
      9. Summary
    2. 11. One Task at a Time
      1. Tasks Can Be Small
      2. Extracting Values from an Object
        1. Applying “One Task at a Time”
        2. Another Approach
      3. A Larger Example
        1. Further Improvements
      4. Summary
    3. 12. Turning Thoughts into Code
      1. Describing Logic Clearly
      2. Knowing Your Libraries Helps
      3. Applying This Method to Larger Problems
        1. An English Description of the Solution
        2. Applying the Method Recursively
      4. Summary
    4. 13. Writing Less Code
      1. Don’t Bother Implementing That Feature—You Won’t Need It
      2. Question and Break Down Your Requirements
        1. Example: A Store Locator
        2. Example: Adding a Cache
      3. Keeping Your Codebase Small
      4. Be Familiar with the Libraries Around You
        1. Example: Lists and Sets in Python
        2. Why Reusing Libraries Is Such a Win
      5. Example: Using Unix Tools Instead of Coding
      6. Summary
  8. IV. Selected Topics
    1. 14. Testing and Readability
      1. Make Tests Easy to Read and Maintain
      2. What’s Wrong with This Test?
      3. Making This Test More Readable
        1. Creating the Minimal Test Statement
        2. Implementing Custom “Minilanguages”
      4. Making Error Messages Readable
        1. Using Better Versions of assert()
        2. Hand-Crafted Error Messages
      5. Choosing Good Test Inputs
        1. Simplifying the Input Values
        2. Multiple Tests of Functionality
      6. Naming Test Functions
      7. What Was Wrong with That Test?
      8. Test-Friendly Development
      9. Going Too Far
      10. Summary
    2. 15. Designing and Implementing a “Minute/Hour Counter”
      1. The Problem
      2. Defining the Class Interface
        1. Improving the Names
        2. Improving the Comments
      3. Attempt 1: A Naive Solution
        1. Is the Code Easy to Understand?
        2. An Easier-to-Read Version
        3. Performance Problems
      4. Attempt 2: Conveyor Belt Design
        1. Implementing the Two-Stage Conveyor Belt Design
        2. Are We Done?
      5. Attempt 3: A Time-Bucketed Design
        1. Implementing the Time-Bucketed Design
        2. Implementing TrailingBucketCounter
        3. Implementing ConveyorQueue
      6. Comparing the Three Solutions
      7. Summary
  9. A. Further Reading
    1. Books on Writing High-Quality Code
    2. Books on Various Programming Topics
    3. Books of Historical Note
  10. Index
  11. About the Authors
  12. Colophon
  13. Copyright

Product information

  • Title: The Art of Readable Code
  • Author(s): Dustin Boswell, Trevor Foucher
  • Release date: November 2011
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781449314217