Defensive Programming

原创 2004年09月26日 16:13:00

In defensive programming, the main idea is that if a routine is passed bad data, it won't be hurt, even if the bad dadta is another routine's fault.

Three genreal ways to handle garbage in
1. Check the values of all data from external sources.
When getting data from a file, auser, the network, or some other external interface, check to be sure that the data falls within the allowable range.
2. Check the values of all routine input parameters.
3. Decide how to handle bad inputs

When an assertion is true, that means everything is operation as expected. When it's false, that means it has detected an unexpected error in the code.
Guidelines for Using Assertions
1. Use error handlng code for conditions you expect to occur; use assertions for conditions that should never occur.
Assertion check for conditions that should never occur. Error handling code check for off-nominal circumstances that might not occur very often, but that have been anticipated by the programmer who worte the code and that need to be handled by the production code.
2. Avoid putting executable code in assertions
Putting code into an assertion raises the possiblity that the compiler will eliminate the code when you turn off the assertion.
3. Use assertions to document perconditions and postconditions
Preconditions and postconditions are part of an approach to program design and development known as "design by contract". when preconditions and postconditions are used, each routine or class forms a contract with the rest of the program.
4. For highly robust code, assert, and then handle the error anyway.

Error Handling Techniques
1. Return a neutral value
Sometimes the best response to bad data is to continue operating and simply return a value that's known to be harmless.
2. Substitute the next piece of valid data
3. Return the same answer as the previous time.
4. Substitue the closest legal value.
5. Log a warning message to a file.
6. Return an error code
7. call an error processing routine/object.
8. Display an error message wherever the error is encountered.

1. Use exceptions to notify other parts of the program about errors that should not be ignored.
2. Throw an exception only for conditions that are truly exceptional.
3. Don't use an exception to pass the buck
If an error condition can be handled locally, handle it locally. Don't throw an uncaught exception in a section of code if you can handle the error locally.
4. Avoid throwing exception in constructors and desctructors unless you catch them in the same place.
5. Throw exceptions at the right level of abstraction.P15
6. Include all information that led to the exception in the exception message.
7. Know the exceptions your library code throws
8. Consider building a centralized exception reporter.

您举报文章:Defensive Programming