• simon.crick (9/25/2013)


    "embrace the idea that code can be wrong" -- Nathan Marz

    Surely this is the wrong approach, as it just gives people an excuse to be lazy.

    Code should NEVER be wrong.

    It is not difficult to write code that works correctly.

    You just need to follow two simple rules:

    1) Be crystal clear about the valid set of inputs, and throw an appropriate exception if the input is not in the valid set.

    2) If you are not sure whether the logic is correct, break your code into smaller functions/procedures until it is 100% clear that it will work correctly in all cases.

    Bugs only arise when people do not follow these simple rules.

    Simon

    That statement is hopelessly optimistic, in my view. Another esential rule is always write defensive code - yes, your point 1 is a part of that, but only a tiny part; we all know that complex operating systems, compilers, and DBMSs contain bugs, and it is necessary to recognise that, to recognise also that we don't know what all those bugs are, and to write code that tries to work despite such bugs do proper error detection, error containment, and error reporting - the whole effor management thing - not just validation of inputs with exception throwing when they are invalid. But the cardinal rule of all, far more important than anything you have said, is first know what the requirement is and often that is in fact the most difficult thing to do.

    Even if one tries to follow all the rules (and there are still more, to do with avoidance of complexity, economy of invention, esthetics, resource consumption, which ought to be stated as part of the requirement but probably won't be because the requirement is almost always incomplete, which is another source of problems) the complexity of the task may be such that human limitations are likely to lead to errors - another function of defensive programming is to detect and contain these as far as possible, but as far as possible often is no going to be as far as perfection and that means that we must accept that our software will contain bugs instead of claiming that we are so perfect that we never make a mistake.

    Tom