Computational Methods in Physics ASU Physics PHY 494

14 Defensive Programming

Note: This lesson draws heavily from, and in some parts quotes directly, the Python Testing lesson developed by Kathryn Huff.

Untested code is broken code. Doing science with untested code is akin to using an experimental device that is uncalibrated, which is generally a bad idea. The best way to write code that works and keeps on working is to assume it's broken, and to build yourself some alarms for when its behavior is outside of what is expected.

This mindset is often called defensive programming.

In this lesson, we will learn about various flavors of testing code, including:

  1. Assertions
  2. Exceptions
  3. Unit Tests

and we will write some of our own, too.

Class material

See the refined version of the live notebook used in class for the detailed lesson: Defensive_Programming.ipynb

Additional resources