Category 3 Star Topics
This is a summary of
http://files.ocs.drexel.edu/courseweb/mcs350-991/lectures/1-19-99/tsld030.htm (Source no longer available)
There are two sides to defensive programming:
- Defensive design -- avoid bugs in the first place
- Simplicity of design
- Minimize coupling (dependency) between classes
- Design so that the proper functionality does not depend on other classes at the same level of design
- Design with error in mind
- Typically error handling has secondary status in the mind of the programmer and is thrown into the code with little thought
- Design by asking/answering a lot of “what if” questions: what should a component do if another part of the program does something unexpected?
- Analyze the design to identify problems early
- Show the design to another group: management, other developers, or outside consultants.
- Writing/presenting a design teaches the designer a lot by making more details explicit in his/her mind.
- Reviewers can provide a new viewpoint on the design different implicit assumptions than the original designer.
- Make all assumptions and conditions explicity: pre- and post- conditions for methods
- A precondition for a method specifies the assumptions that are made on the input parameters and the state of the object when the method is invoked
- A postcondition specifies assumptions made on the output values of the method and the state of the object upon return.
- Defensive coding -- take steps to localize problems
- Be suspicious
- public methods should check parameters for proper ranges
- check that called methods return valid values
- check for error conditions returned by other routines
- check intermediate values/class fields when it can be done inexpensively
- Ensure that variables and fields are initialized to meaningful values
- Keep the code simple
- Do a code review: double-check code, read it critically
- Use assertions liberally
- Use exceptions only to indicate and return error conditions
- Exceptions throw types that are defined as “exception classes” (even though C++ lets any type be an exception)
- If a routine can throw an exception declare it to do so
Warning: trying to make code handle any conceivable error will not result in a simple design or simple code. Sometimes people who claim to be practicing defensive programming end up with lots of checks in their code, making it complex and hard to change. You might argue that this is not true defensive programming, but they thought it was. Simplicity is very important, and I'd rather have a program that I understand that fails under well understood conditions than code that I don't understand, but I can't make it crash.
Category Coding Category Definitions
( Topic last updated: 2009.12.04 02:34:08 PM )