On Defensive Coding

CS 300 Lecture 3.2

Bart Massey 2013-10-17

Overview

  • Misc notes
  • Coding From Pseudocode Concluded
  • Defensive Coding

Misc Notes

Coding From Pseudocode Concluded

(In-class coding demo.)

Defensive Coding

  • "Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?" --Brian Kernighan, The Elements of Programming Style

  • Fundamental Idea: Code should be implemented in such a way that

    • Defects are less likely to cause faults, and faults to cause failures

    • Diagnosis of root causes of failures is as easy as possible

When to Code Defensively

  • When it is free. For example, consider "less-than" in

    for (int i = 0; i < 10; i++)

  • When it is likely to achieve payback. For example

    if (s != 0) free(*s);

  • As a matter of instrumentation

    if (s == 0) { log("unexpected null pointer s"); return; }

How to Code Defensively: Errors

  • Code should fail rather than go on when something's broken

    • Assertions!!!!
    • Mandatory error reporting
    • Error variable method :-(
    • Status return method
    • Marked result method
    • Thrown exception method
  • When code must not fail, errors must be caught and handled

    • Advantage of thrown exception: less intermediate code

How to Code Defensively: Instrumentation

  • Plan instrumentation in design

    • What/where/how will things be logged?
  • Instrument overall program status, not just bugs

  • Don't be afraid to build instrumentation infrastructure

    • Special program arguments / environment variables vs recompile
    • Special functions for checking and reporting errors conveniently

My Program Works, But I Don't Know Why

  • This is a kind of fail.
Last modified: Thursday, 17 October 2013, 9:47 AM