Saturday, March 5, 2011

Bulletproof code.

What has been helping me out is the phrase: "Code that cannot fail is infinitely easier to maintain then code that has many paths through it which might fail."

Murphy's law: "What can go wrong WILL go wrong". So go over every line of code and ask: "How might this function do something unintended?". If you find any answer to that question then you need to change how the function works until the answer is: "This function physically cannot do something unintended". If the hardware and compiler are working to specification then the ONLY path through this code is the correct way through (or a pretty exception/error that tells you what the programmer/user did wrong or what the hardware/compiler failure was).

For example: you have a function calculate() which takes a collection of Strings which represents items to process. The problem is that function foo() might run incorrectly and some String items may become invalid or incorrect. Then calculate() will make its best attempt, then calculate may throw an exception/error or worst of all, it may work. The solution here is to make it physically impossible for the items in the list to become invalid/wrong, don't use an array of String, use an array of class Student/Airplane/Book/ProcessItem which has a constructor which validates its own existence as soon as it is made, it will produce a runtime error (or better yet a compile time error) the instant the programmer/user made a mistake.

The millions of unintended paths through calculate() which may throw a cryptic runtime exception has been eliminated. Imagine how much easier it is to diagnose a "InputProcessItemException" than a cryptic off-by-one error inside calculate();

1 comments:

  1. "Murphy's Law", Well I'd say that is absolute genius to say this with programming in mind.

    I hope you post more.

    Why don't you promote your site? Another saying, "build a better mouse trap and they'll beat a path to your door.", problem is they have to see the mouse trap.

    :)

    ReplyDelete