Robust Code - Advanced Programming Techniques (2011, 2013)

Advanced Programming Techniques (2011, 2013)

Appendix A. Robust Code

115

There is an old computer programming joke that goes like this. A consultant went to a large company to teach the software engineers in the company. At the beginning of the class she said to the students, “If you got on an airplane and realized that your team had written the software that runs the airplane, how many of you would be afraid for your life and get off the plane?” Every student except one put his hand up. The consultant looked at the one student who didn’t raise his hand and asked, “What does your team do differently so that you wouldn’t be afraid to ride on the airplane?” The student answered, “Ha! if my team had written the software, the plane would never even get off the ground. I’d be perfectly safe.”

Below are some programming practices that if you follow will make your software more robust (fewer errors) and help you rest easy on a working airplane for which you and your team wrote the software.

1. Follow generally accepted coding standards and conventions, including naming conventions.

2. Whenever possible, write simple, straight forward code. For example when writing in JavaScript, Java, C++, and C do not use the left shift operator (<<) to multiply by a power of two. Instead use multiplication (*) and rely on the compiler to generate fast code.

3. Minimize the number of execution paths through your code. (See the section Find a Range in chapter 1 of this book for an example of how to do this.)

4. Write each function to perform one and only one task.

5. Unless the function is extremely small and simple (ten lines of code or less), write each function with only one exit point (return statement).

6. When writing in a language that has exceptions, never return error codes from a function. Instead throw exceptions to indicate an error.

7. Turn on compiler warnings and never ignore them.

8. Write and use assertions. Test primarily with assertions turned on.

9. Write and execute unit tests and don’t ignore test failures.

10. Consider writing a tricky algorithm twice, once with a straight forward, slow solution and once with a sophisticated, fast solution. In the debugging version of your program use the slow solution to verify the results of the fast solution.