Defencive programming

sariazraa 948 views 15 slides Feb 17, 2014
Slide 1
Slide 1 of 15
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15

About This Presentation

Defensive Programming, Code Complete
Author : Steven C. McConnell.


Slide Content

Prof. Asha N 1
Defensive Programming
Code Complete
Author : Steven C. McConnell.

Prof. Asha N 2
Defensive Programming
You take responsibility for protecting yourself
even when it might be the others fault.
Eg: if a routine is passed bad data it won’t
be hurt, even if the bad data is another
routine’s fault

Prof. Asha N 3
Protecting Your Program
From Invalid Inputs
“Garbage in, garbage out.”
A good program uses “garbage in, nothing
out”; “garbage in, error message out”; or “no
garbage allowed in” instead.

Prof. Asha N 4
Contd….
three general ways to handle garbage in
1.Check the values of all data from external
sources
2.Check the values of all routine input
parameters
3.Decide how to handle bad inputs

Prof. Asha N 5
Assertions
An assertion is code - usually a routine or macro.
an assertion is
True - means everything is operating as
expected.
False - means it has detected an
unexpected error in the code.
An assertion takes two arguments:
1. a Boolean expression that describes the
assumption that’s supposed to be true
2. a message to display if it isn’t.

Prof. Asha N 6
Contd…
assert denominator != 0 : "denominator is unexpectedly equal to
0.";
denominator != 0 , is a boolean expression that
evaluates to True or False.
The second argument is a message to print if the first
argument is False—that is, if the assertion is false.
C++ Example of an Assertion Macro
#define ASSERT( condition, message ) { \
if ( !(condition) ) { \
fprintf( stderr, "Assertion %s failed: %s\n", \
#condition, message ); \
exit( EXIT_FAILURE ); \
} \
}

Prof. Asha N 7
Guidelines for Using Assertions
Use error handling code for conditions you expect to occur; use
assertions for conditions that should never occur
Avoid putting executable code in assertions

–Visual Basic Example of a Dangerous Use of an Assertion
Debug.Assert( PerformAction() ) ' Couldn't perform action
–Visual Basic Example of a Safe Use of an Assertion
actionPerformed = PerformAction()
Debug.Assert( actionPerformed ) ' Couldn't perform action
Use assertions to document preconditions and postconditions
For highly robust code, assert, and then handle the error anyway

Prof. Asha N 8
Error Handling Techniques
Return a neutral value
Substitute the next piece of valid data
Return the same answer as the previous time
Substitute the closest legal value
Log a warning message to a file
Return an error code
Call an error processing routine/object
Display an error message wherever the error is encountered
Handle the error in whatever way works best locally
Shutdown

Prof. Asha N 9
Exceptions
Exceptions are a code can pass along errors or
exceptional events to the code that called it.

Code that has no sense of the context of an error can
return control to other parts of the system that might
have a better ability to interpret the error and do
something useful about it.

Prof. Asha N 10
Exceptions
Benefits of exceptions and avoiding the difficulties often associated with
them.
Use exceptions to notify other parts of the program about errors that
should not be ignored
Throw an exception only for conditions that are truly exceptional
Don’t use an exception to pass the buck
Avoid throwing exceptions in constructors and destructors unless you
catch them in the same place
Throw exceptions at the right level of abstraction
Include all information that led to the exception in the exception
message
Avoid empty catch blocks
Know the exceptions your library code throws
Consider building a centralized exception reporter

Prof. Asha N 11
Contd….
Bad Java Example of a Class That Throws an Exception at an Inconsistent
Level of Abstraction
class Employee {
...
public TaxId getTaxId() EOFException {
...
}
...
}
Good Java Example of a Class That Throws an Exception at a Consistent
Level of Abstraction
class Employee {
...
public TaxId getTaxId() throws EmployeeDataNotAvailable {
...
}
...
}

Prof. Asha N 12
Barricade Your Program to Contain the
Damage Caused by Errors

Barricades used to be called “firewalls,” but the term
“firewall” now commonly refers to port blocking.
Check data crossing the boundaries of a safe
area for validity and respond sensibly if the data
isn’t valid

Prof. Asha N 13
Relationship between Barricades and
Assertions

Routines that are outside the barricade should use error handling
because it isn’t safe to make any assumptions about the data.

Routines inside the barricade should use assertions, because the
data passed to them is supposed to be sanitized before it’s
passed across the barricade.

Prof. Asha N 14
Debugging Aids

Introduce Debugging Aids Early
Use Offensive Programming
Use version control and build tools like make
Use a built-in preprocessor
Use debugging stubs

Prof. Asha N 15
Determining How Much Defensive Programming
to Leave in Production Code

Leave in code that checks for important errors
Remove code that checks for trivial errors
Remove code that results in hard crashes
Leave in code that helps the program crash gracefully
Log errors for your technical support personnel
See that the error messages you leave in are friendly
Tags