Crash Program Earlier

Crashing the program earlier has two advantages: the program is dead, and the resources are reclaimed by the system. A dead program is better than a crippled one. The Pragmatic Programmer

To do this, always check the return value of a function or method of a class with the expected value. Crash the program as soon as there’s a problem. Combining with some software engineering practices such as Design by Contract (DBC), it will give a strong guarantee that the system will not put up unexpected operations.

We can quickly do this using a macro function# :

#define CHECK(LINE, EXPECTED)                       \
{                                                   \
int rc = LINE;                                      \
if (rc != EXPECTED)                                 \
ut_abort(__FILE__, __LINE__, #LINE, rc, EXPECTED);  \
}

void ut_abort(char *file, int ln, char *line, int rc, int exp) {
fprintf(stderr, "%s line %d\n'%s': expected %d, got %d\n",
        file,
        ln,
        line,
        exp,
        rc);
exit(1);
}
Links to this page
  • The Pragmatic Programmer

    If there is something that surprise you, reevaluate your assumptions. Don’t just “know” your code works, prove it, in this context, with this data, with these boundary conditions. Add new test# to it, 202207091736# or put some 202207091744#.

  • “It Can’t Happen”

    If, for example, you have stumbling across the application codebase, run it, and found something that surprise you, reevaluate your assumptions, be willing to debug it#. Don’t just “know” your code works, prove it, in this context, with this data, with these boundary conditions. Add new test# to it, Crash Program Earlier# or put some Assertions#. You can go further by adopting Defensive Programming#, enforcing checks on precondition, postcondition and class invariant by Design by Contract (DBC)#.

  • Design by Contract (DBC)

    If any of these violated during the compile time or runtime, the building of the program should fail or the program simply crashed. The alternative to this is to raise an #exception when such violations are encountered. Then, the programmer will handle them in care and crash the program gracefully if possible.

#debugging #oop #functional-programming