Memory Management

  • Is hard in C++

  • Any non-trivial memory management should be inspected by someone else

  • Learn to use memory analysis tools, e.g. valgrind

  • RAII: ensure that memory is allocated at first use, freed after last use

The Pairing Principle

  • Every alloc should have a free

  • Every open should have a close

  • Every time you do something, think of and note "obligations" produced by it

    • Ideally, "discharge" those right away

Unit Control Flow Made Easy

  • Idea: Successive strengthening of invariants

    • Start by picking off special cases

      • Assertions: fail for unhandled cases
      • Recursion: get base case
      • Special cases: early return
    • Each line of the unit you should know more about what you're working with

    • At the end of the routine you should just be able to dispatch stuff

    • break and continue are your friends

  • Idea: Case analysis

    • Conditionals and case statements are the same thing
  • Idea: Hoare clauses and loops

Indentation Is The Enemy

  • Nesting depth only thing that has been shown to correlate strongly with poor code quality

  • Untangle logic

  • Early return vs else

  • Splitting out subunits

Idiom Is Your Friend

  • Write things the way other people write them in C++

    • Maybe there's a reason
    • Regardless, it means others can work with your code
  • Don't fight the language

  • Follow the coding standard

Coupling and Cohesion

  • Every unit tells a story

  • If a unit tells two unrelated stories, break it up

  • If a unit needs a lot of information to tell its story, put it with the information

    • This is the idea behind OOP

Error Handling

  • C++ has an exception mechanism

  • All error returns must be handled

    • Many can be handled with assertions, but not all
  • This is a real design thing


  • Clarifying comments at the top of interesting units

    • Describe non-obvious features of parameters and results
  • Block comments on top of unit blocks

  • Use XXX comments

  • Comment data structures

  • Comments should not restate the program

  • Comment anything that might be mysterious

    • Or better yet fix the mystery
  • Use a comment-doc tool with C++

Last modified: Monday, 26 October 2020, 12:35 AM