Defensive Programming - Lesson 8


  • How can I make my programs more reliable?


  • Explain what an assertion is.
  • Add assertions that check the program’s state is correct.
  • Correctly add precondition and postcondition assertions to functions.
  • Explain what test-driven development is, and use it when creating new functions.


Alternate video link.

Jupyter Notebook File

Please use the Jupyter notebook named "08DefensiveProgramming.ipynb" for this lesson. If you haven't downloaded them already, you may find them here.

Key Points

  • Program defensively, i.e., assume that errors are going to arise, and write code to detect them when they do.
  • Put assertions in programs to check their state as they run, and to help readers understand how those programs are supposed to work.
  • Use preconditions to check that the inputs to a function are safe to use.
  • Use postconditions to check that the output from a function is safe to use.
  • Write tests before writing code in order to help determine exactly what that code is supposed to do.