Skip to Main Content
Becoming a Better Programmer
book

Becoming a Better Programmer

by Pete Goodliffe
October 2014
Intermediate to advanced content levelIntermediate to advanced
362 pages
7h 49m
English
O'Reilly Media, Inc.
Content preview from Becoming a Better Programmer

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

How Functional Programming Can Improve Testing, Reuse, and Maintenance in Your Current Codebase

How Functional Programming Can Improve Testing, Reuse, and Maintenance in Your Current Codebase

Eric Normand

Publisher Resources

ISBN: 9781491905562Errata Page