Chapter 9. Expect the Unexpected
Be Prepared…the meaning of the motto is that a scout must prepare himself by previous thinking out and practicing how to act on any accident or emergency so that he is never taken by surprise.Robert Baden-Powell
They say that some people see the glass half full, some see it half empty. But most programmers don’t see the glass at all; they write code that simply does not consider unusual situations. They are neither optimists nor pessimists. They are not even realists. They’re ignore-ists.
When writing your code, don’t consider only the thread of execution that you expect to happen. At every step, consider all of the unusual things that might occur, no matter how unlikely you think they’ll be.
Errors
Any function you call may not work as you expect.
-
If you are lucky, it will return an error code to signal this. If so, you should check that value; never ignore it.
-
The function might throw an exception if it cannot honor its contract. Ensure that your code will cope with an exception bubbling up through it. Whether you catch the exception and handle it, or allow it to pass further up the call stack, ensure that your code is correct. Correctness includes not leaking resources or leaving the program in an invalid state.
-
Or the function might return no indication of failure, but silently not do what you expected. You ask a function to print a message. Will it always print it? Might it sometimes fail and consume the message?
Always consider ...
Get Becoming a Better Programmer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.