jump to navigation

NOTE: The spam filter is being unusually aggressive. If you comment does not immediately appear, it has simply been placed in moderation and I will approve it as quickly as possible. Thank you for your patience.

"Murphy was an optimist!"

Today’s Programming Advice – Code for the impossible May 14, 2009 12:26 pm

Posted by Doug McCaughan in : Programming, Quality Assurance, Technology
, trackback

Always code for the impossible case! The impossible tends to happen surprisingly often. The programming language is irrelevant. Whether you code in C, C++, F#, ColdFusion, PHP, JavaScript, or whatever, conditional statements and case statements should always accommodate the unexpected value.

Right now I am dealing with some code that involves a list of 1 or more items. The actionable part of the code involves clicking on one of the items in the list therefore at least 1 item must exist. Having zero items is impossible because if there were no items then I could not click on the item to start the actionable part of the code. So why waste time coding of the zero items case? This is not the best example since this is a multi-user, client/server web application and the zero case can be created quite simply by having two users pull up the same list and then one user deletes an item before the other. But that answers the question of why waste time coding for the impossible? Because it does happen. My code frequently has conditional statements that end with a default case or a special case that simply outputs "This is impossible. Please contact the administrator." and includes some debugging information. In my career, doing this has saved me hours and hours of debugging time on more than a couple of occasions.

Comments after advertisement


1. Stormare Mackee - May 15, 2009

Also known as defensive programming. The pitfall with defensive programming is that it can hide fundamental flaws in the program logic. The worst case of “preparing for the impossible” is swallowing exceptions, that is, ignoring a fault in order to not “crash” the application in front of the end user. In case of a real fault, it’s better to let the app crash and burn rather than give the user the choice of continuing execution with application in an unstable state.

2. Doug McCaughan - May 15, 2009

That’s a great comment! And I agree that swallowing exceptions is a horrible practice.