Transcript Download

(0721385)
First Semester 2014-2015
Dr. Samer Odeh Hanna (PhD)
http://philadelphia.edu.jo/academics/shanna
Office: IT 327
Software Construction
1
Chapter 3: Defensive Programming
Software Construction
2
Introduction

The idea of defensive programming is based on
defensive driving

In defensive programming, the main idea is that if a
routine is passed bad data, it won't be hurt, even if the
bad data is another routine's fault.
Software Construction
3
3.1 Protecting Your Program from Invalid Inputs
A good program never put out garbage, regardless of what
it takes in. A good program uses:
"Garbage in, nothing out"
 "Garbage in, error message out"
 "No garbage allowed in"

Software Construction
4
There are three general ways to handle
garbage in:

Check the values of all data from external sources
 Attempt buffer overflows
 Inject SQL commands
 Inject HTML or XML code and so on
Check the values for all routine input parameters
 Decide how to handle bad inputs

Software Construction
5
3.2 Assertions

An assertion is code that is used during development that
allows a program to check itself as it runs. When an
assertion is true, that means everything is operating as
expected, when it is false, that means it has detected an
unexpected error in the code.
assert denominator != 0 : "denominator is
unexpectedly equal to 0.";
Software Construction
6
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 into assertions

Visual Basis example of a dangerous use of an assertion
Debug.Assert (PerformAction( )
) ' Could no perform action
Visual Basis example of a safe use of an assertion
actionPerformed = PerformAction( )
Debug.Assert (actionPerformed )
Software Construction
7
Cont.

Use assertions to document and verify preconditions and
Postconditions
Visual Basic example of using assertions to document preconditions and Postconditions
Private Function Velocity (
ByVal latitude As Single,
ByVal longtitude As Single,
ByVal elevation As Single
) As Single
' Preconditions
Debug.Assert ( -90 <= latitude And latitude <=90)
Debug.Assert ( 0 <= longitude And longitude <360)
Debug.Assert ( -500 <= elevation And elevation <= 75000)
' PostConditions
Debug.Assert ( 0 <= returnVelocity and returnVelocity <=600 )
' return value
Velocity = returnVelocity
End Function
Software Construction
8

For highly robust code, assert and then handle the error anyway
Visual Basic example of using assertions to document preconditions and Postconditions
Private Function Velocity (
ByVal latitude As Single,
ByVal longitude As Single,
ByVal elevation As Single
) As Single
Assertion code
' Preconditions Debug.Assert ( -90 <= latitude And latitude <=90)
Debug.Assert ( 0 <= longitude And longitude <360)
Debug.Assert ( -500 <= elevation And elevation <= 75000)
…..
' Sanitize input data. Values should be within the ranges asserted above
' but if a value is not within its valid range, it will be changed to the
' closet legal value
If ( latitude < -90 ) Then
Code that handles bad input data at run-time
latitude = -90 ElseIf ( latitude > 90 ) Then
latitude = 90
End If
IF ( longitude < 0 ) Then
Longitude = 0
ElseIF ( longitude > 360 ) Then
…
End Function
Software Construction
9
3.3 Error-Handling Techniques
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
Return a neutral value
Substitute the next piece of valid data
Return the same answer as previous time
Substitute the closet 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
Shut down
Software Construction
10
Differences between assertion and error
handling techniques
Assertion
Error Handling Technique
An assertion is code that is used
during development
Error handling techniques is code that
is used during development and after
delivery
assertions for conditions that should
never occur
error-handling code is used for
conditions you expect to occur
the corrective action is to change the
the corrective action is merely to
program's source code, recompile, and handle an error gracefully
release a new version of a software.
Software Construction
11
Robustness vs. Correctness
Correctness means never returning an inaccurate result;
returning no result is better than returning an inaccurate
result.
 Robustness means always trying to do something that
will allow the software to keep operating, even if that
leads to results that are inaccurate sometimes.
 Some applications tend to favor correctness to
robustness and others favor robustness to correctness.

Software Construction
12
3.3 Exceptions
Exceptions are a specific means by which code can pass
along errors or exceptional events to the code that called
it. If code in one routine encounters an unexpected
condition that it does not know how to handle, it throws
an exception, essentially throwing up its hands and
yelling, "I do not know what to do about this – I sure hope
somebody else knows how to handle it!"
 Visit http://www.dotnetperls.com/exception for examples

Software Construction
13
Example
using System;
class Program
{
static void Main()
{
try
{
int value = 1 / int.Parse("0");
Console.WriteLine(value);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Software Construction
14
Custom Exception Example
using System;
class TestException : Exception
{
public override string Message
{
get { return "This exception means something bad happened"; }
}
}
class Program
{
static void Main()
{
try
{
throw new TestException();
}
catch (TestException ex)
{
Console.WriteLine(ex.Message);
}
}
}
Software Construction
15
Exceptions (Cont.)
Suggestions for realizing the 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
 If an error condition can be handled locally, handle it
locally
 Avoid throwing exceptions in constructors and
destructors
 Throw exceptions at the right level of abstraction
 Include in the exception message all information that
led to the exception
Software Construction
16
Cont.
Avoid empty catch blocks
 Standardize your project's use of exceptions
 Consider alternatives to exceptions

Software Construction
17
3.4 Barricade
Barricade your Program to Contain the Damage
Caused by Errors
 Barricades are a damage-containment strategy
 One way to barricade for defensive programming
purpose is to design certain interfaces as boundaries to
"safe" areas

Software Construction
18
Relationship between Barricades and Assertions
Routines that are outside the barricade should use error
handling
 Routines inside the barricade should use assertions

Software Construction
19
Questions?
Software Construction
20