How should a program behave?
April 24th, 2005 by Samuel TardieuI always tell my compilation class students that there are two steps to follow when developping a new program:
- the program must accept any valid input and produce accurate results; the result of feeding the program with invalid input is undefined, it can either crash or silently produce wrong results;
- the program must reject any invalid input.
I see too many programmers try to implement the second phase before finishing the first one. It is true that implementing only the first one adds a burden onto the user, as he must provide valid input. But when the user makes no mistake, the program won’t either. However, as weird as it may seem, the second step is often the most difficult to achieve.

April 24th, 2005 at 21:33
Unfortunately, in my experience, accepting invalid input is more often than not the symptom of a poor design that happens to produce correct results for valid input by sheer luck rather than by construction.
Achieving rejection of all invalid inputs often requires fundamental changes that eventually lead to a correct design, which is unsuprisingly difficult.
As the saying goes, for every complicated problem, there is one solution that is simple, elegant, and wrong. This is usually the one that you stumble upon in the first phase.
April 25th, 2005 at 0:52
Thomas, I could not agree more. However, when working on an assignment, or on an program which is needed really fast (such as a Forth compiler for a robotics cup which takes place a few days after you start writing the compiler), it is much more important in my opinion to produce valid output for any valid input than to reject any invalid code.