SlideShare a Scribd company logo
NDSU CSCI 717
Software Construction
Defensive Programming
Textbook
Steve McConnell. Code Complete: A Practical Handbook of
Software Construction. 2nd Edition. Microsoft Press, 2004.
Chapter 8.
2
Outline
Protecting from Invalid Inputs
Using Assertions
Error-Handling Techniques
Using Exceptions
Barricade/Firewall Your Program
Debugging Aids
Be Defensive about Defensive Programming
3
Protecting from Invalid Inputs
Garbage in, garbage out?
Mark of sloppy nonsecure program
Garbage in, nothing/error message out
No garbage allowed in
Defensive programming
If a routine is passed bad data, it won’t be hurt, even if the bad
data is another routine’s fault.
Check values of all data from external sources
Sources: file, user, network
Allowable range: String vs security problem
Check values of all routine input parameters
Decide how to handle bad inputs
4
Assertions
To document assumptions made in the code and to flush out
unexpected conditions
An input/output parameter in its expected range
A file/stream is open (or closed) when a routine begins (or
ends) executing
A file/stream is at the beginning
A file/stream is open for read-only, write-only, etc.
An input-only variable is not changed
A pointer is non-null
A container is empty (or full) when a routine begins (or ends)
executing
Match two results
5
Assertion Mechanism
Java assertions
Assert denominator!=0 : “denominator is 0”
Define your own
#define ASSERT(condition, message) {
if (!(condition)) {
LogError(“Assertion failed: ”, #condition, message);
exit(EXIT_FAILURE);
}
}
6
Using Assertions: Guidelines
Use error-handling for conditions you expect to occur; use
assertions for condition that should never occur
Error handling typically checks for bad input
Assertions check for bugs in the code
Avoid putting executable code into assertions
The compiler will eliminate the code when the assertions are
turned off
Use assertions to document/verify pre/postconds
For highly robust code, assert and then handle the error anyway.
E.g. change an invalid input to the closest legal value
7
Error-Handling Techniques
Return a neutral value (known to be harmless)
Examples: 0, empty string, default color
Substitute the next place of valid data
Encounter a corrupted record when reading from a DB
Return the same answer as the previous time
Thermometer-reading code does not get a reading one time
Substitute the closest legal value
Log a warning message to a file
Return an error code
8
Error-Handling Techniques
Call an error processing routine/object
Centralize error handling in a global routine/object
Display an error message wherever the error is encountered
Handle the error in whatever way works best locally
Individual developers have the flexibility
Risky: spread UI code throughout the system
Shut down
Safety critical applications
9
Using Exceptions: Suggestions
Use exceptions to notify other parts about errors that should not
be ignored
Throw an exception only for conditions that are truly
exceptional
Cannot be addressed by other coding practices
Don’t throw an uncaught exception if you can handle the error
locally
Avoid throwing exceptions in constructors /destructors unless
you catch them in the same place
The rule for how exceptions are processed become very
complicated
C++: destructors are not called unless an object is fully
constructed
10
Using Exceptions: Suggestions - cont
Throw exceptions at the right level of abstraction
The exceptions thrown are part of the interface
Class Employee {
public TaxId GetTaxId() throws EOFException
public TaxId GetTaxId() throws EmployeeDataNotAvailable
}
Include in the exception message all info that led to the
exception
Avoid empty catch blocks
Know the exceptions your library code throws
Consider building a centralized exception reporter
Standardize your project’s use of exceptions
Consider alternatives to exceptions
11
Barricade/Firewall Your Program
A building’s firewall prevents fire from spreading from one part
of the building to another part
Barricade your program to contain the damage caused by errors
Designate certain interfaces as boundaries to safe areas
Check data crossing the boundaries of a safe area for validity,
and respond sensibly if the data is invalid
Class Level
Public methods assume the data is unsafe
Private methods can assume the data is safe
12
Debugging Aids
Introduce debugging aids early
Don’t automatically apply production constraints to the
development version
Differences: speed, resource, etc
Use offensive programming
Exceptional cases should be handled in a way that makes them
obvious during development and recoverable when production
code is running. (Howard & Leblanc 2003, Writing secure code)
Default clause of case statement
Development - warning: “hey, another case here! Fix it”
Production - something more graceful, e.g. error-log
Plan to remove debugging aids
13
Programming Offensively
Make sure asserts abort the program
Don’t allow programmers to get into the habit of just hitting the
Enter key to bypass a known problem
Completely fill any memory allocated to detect memory
allocation errors
Completely fill any files/streams allocated to flush out any file-
format errors
Be sure the code of default/else clause fails hard (aborts the
program) or is o.w. impossible to overlook
Fill an object with junk data just before it is deleted
…
14
Be Defensive about Defensive Prog.
Think about where you need to be defensive.
Set you defensive programming priorities accordingly.
15
NDSU CSCI 717
Software Construction
Design By Contract
Textbook
Bertrand Meyer. Object-Oriented Software Construction, 2nd
Edition, Prentice-Hall PTR, 1997. Chapters 11 and 12.
2
Outline
Correctness Formula
Assertions and Contracts
Class Invariants
When Is a Class Correct?
ADT Connection
Loop Invariants and Variants
Using Assertions
Exception Handling
3
Is x := y + 1 Correct?
“Make sure that x and y have different values”
“Make sure that x has a negative value”
Correctness is a relative notion.
Need to get not only the program but also a precise description
of what it is supposed to do
Specification!
4
Reliability: Correctness & Robustness
Correctness
The ability of software products to perform their exact tasks, as
defined by their specification
Robustness
The ability of software systems to react appropriately to
abnormal conditions
Need a mechanism for expressing and validating correctness
arguments.
5
Reliability via Design By Contract
Viewing the relationship between a class and its clients as a
formal agreement
Expressing each party’s rights and obligations.
Through a precise definition of every module’s claims and
responsibilities, we hope to attain a significant degree of trust
in large systems.
6
Correctness Formula
{P} A {Q} – a.k.a. Hoare Triples
A – operation/routine
P – precondition
Q – postcondition
“Any execution of A, starting in a state where P holds, will
terminate in a state where Q holds.”
7
Correctness Formula: Example
{x >= 9} x := x + 5 {x >= 13}
Given {x >= 9}, the most interesting postcond?
{x >= 14}
Strongest possible
Given {x>=13}, the most interesting precond?
{x>=8}
Weakest possible
8
Weak and Strong Conditions
P1 is stronger than P2 if P1 implies P2 (P1≠P2)
i.e. P2 is weaker than P1
legitimate to speak of True as the weakest and False as the
strongest of all possible assertions.
Every proposition implies True
False implies every proposition
9
{P}A{Q}: Employee Perspective
Job Ad: “We are looking for someone whose work will be to
start from initial situations as characterized by P, and deliver
results as defined by Q”.
Assume a friend is looking for a job and comes across several
such ads, all with similar salary and benefits, but differing by
their Ps and Qs.
Lazy friend wants the easiest possible job: sinecure
Recommend for P/Q: choose a job with a weaker or stronger
precondition/postcondition?
10
{P}A{Q}: Employee Perspective-cont
Sinecure 1: {False} A {…}
The stronger the P, the easier for the employee
Only have to deal with a more limited set of situations
False, the strongest possible, is never satisfied
Any request to execute A will be incorrect, the fault lies not
with A but with the requester
Who did not observe the required precondition
Whatever A does or does not do may be useless, but A is always
correct!
Do you want/know any of such jobs?
11
{P}A{Q}: Employee Perspective-cont
“Obvious — it is the only job where the customer is always
wrong”
why a famous police chief had chosen his career.
12
{P}A{Q}: Employee Perspective - cont
Sinecure 2: {…} A {True}
A strong postcond is bad news - you have to deliver more
results.
The weaker the Q, the better for the employee.
True, the weakest possible, is satisfied by all states
Sinecure1 and Sinecure2, which is better?
13
{P}A{Q}: Employee Perspective - cont
With Sinecure1, A is always correct!
No states satisfy P, so it does not matter what A does, even if
A’s execution would go into an infinite loop or crash the
computer.
With Sinecure 2, there must be a final state.
The final state does not need to satisfy any specific properties,
but it must exist.
“You need to do nothing, but must do it in finite time”
Sinecure 2 is only the “second best” job!
14
{P}A{Q}: Employer Perspective
Everything is reversed.
A weaker precond is good news: a job that handles a broader set
of input cases
A stronger postcond means more significant results
For contracts between clients and suppliers, a benefit for one is
an obligation for the other!
15
Introducing Assertions into Programs
Assertion
An expression stating a property that some entities may satisfy
at certain stages of program execution.
Notation: predicates+ extensions
; and
: between label and component
n > 0 ; x /= Void
Positive: n > 0
Not_void: x /= Void
16
Preconditions and Postconditions
Routines are characterized by strong semantic properties,
independent of specific representation
remove and item are only applicable if the number of elements
is not zero.
put increases the number of elements by one; remove decreases
it by one.
Require: precondition stating the properties that must hold
whenever the routine is called
Ensure: postcondition stating the properties that the routine
guarantees when it returns.
17
Stack
class STACK1 [G]
feature -- Access
count: INTEGER is
-- Number of stack elements
item: G is
-- Top element
require // may not be applied to an empty stack
not empty
do
…
end
18
Stack: status report & element change
feature -- Status report
empty: BOOLEAN is
-- Is stack empty?
do … end
full: BOOLEAN is
-- Is stack representation full?
do … end
feature -- Element change
put, move (next two slides)
19
Stack: put
put (x: G) is
-- Add x on top.
Require // put may not be called
not full
do
…
ensure
not empty // the stack may not be empty
item = x // its top is the element just pushed
count = old count + 1 // count increased by one
end
20
Stack: remove
remove is
-- Remove top element.
require // may not be applied to an empty stack
not empty
do
…
ensure
not full // the stack may not be full
count = old count – 1 // count decreased by 1
end
21
Contracting for Software Reliability
Contract
require pre and ensure post with a routine r
A pre/postcond pair for a routine is the contract that the routine
(supplier) defines for its callers (clients)
Rights and Obligations
“If you promise to call r with precond satisfied then I, in return,
promise to deliver a final state in which postcond is satisfied.”
The precond is an obligation for the client and a benefit for the
supplier.
The postcond is a benefit for the client and an obligation for the
supplier.
22
Obligations and Benefits: StackputObligationsBenefitsClient
(Satisfy precondition:)
Only call put (x) on a non-full stack.
(From postcondition:)
Get stack updated: not
empty, x on top (item yields x, count increased by
1).Supplier(Satisfy postcondition:)
Update stack to have x on top (item yields x), count increased
by 1, not empty.(From precondition:)
Simpler processing thanks to the assumption that stack is not
full.
23
Non-Redundancy Principle
Under no circumstances shall the body of a routine ever test for
its precondition.
A precondition is a benefit for the supplier;
If the call does not satisfy the precond, the routine is not bound
by the postcond - it may do what it pleases
Advantages
Simplicity
“The more we write, the more we will have to write”.
Performance
Zen–style paradox – “get more reliability the best policy is
often to check less”
Reverse of defensive programming
A redundant check might not help,but at least it will not hurt
24
Understanding Assertions
Assertions are no input checking mechanism
Concern: software-to-software communication, not software-to-
human or software-to-outside-world.
In obtaining information from the outside you cannot rely on
preconditions - use input validation or “filter”
Assertions are not control structures
Assertions express correctness conditions.
If sqrt handles negative arguments a certain way, and non-
negatives another way, a require clause is not what you need.
25
Who’s Fault?
Programmer A
double x = -1;
double y = sqrt(x);
assert abs(y*y-x)<eps
// failure
26
Programmer B
double sqrt(double x)
{
//…
}
Assertion Violation Rules
A run-time assertion violation is the manifestation of a bug.
A precondition violation - a bug in the client
The client did not observe its part of the deal.
A postcondition violation - a bug in the supplier.
The supplier was not able to fulfill its contract.
27
Precondition Design
Demanding
Assign the responsibility to clients - the condition will appear
as part of the routine’s precondition
An experienced contractor expects his clients to “do their
homework” before calling on him;
He has no trouble finding business, and will reject requests that
appear too broad or unreasonable.
Tolerant
The condition will appear in an if- then or an equivalent control
structure in the routine.
A freshly established consulting practice, whose owner is so
desperate for business
He will take anything
28
28
Tolerant Version of remove
remove is
-- Remove top element
// no precondition
do
if empty then
print ("Error: attempt to pop an empty stack")
else
count := count – 1
end
end
29
Demanding in Design by Contract
Demanding does not mean to produce routines that assign all
things to all clients.
Insists that each routine
Do a well-defined job and do it well
Correctly, efficiently, generally enough to be reusable by many
clients
Specify clearly what cases it cannot handle.
Only applicable if preconds remain reasonable
O.W. require False makes any routine body correct
30
Reasonable Precondition Principle
Every routine precond in a “demanding” design approach must
satisfy these requirements:
The precond appears in the official documentation distributed to
authors of client modules.
It is possible to justify the need for the precondition in terms of
the specification only.
Examples
remove’s precond: not empty
sqrt’s precond: x>0
Logical requirements, not for supplier’s implementation
convenience
31
Precondition Availability Rule
To be satisfiable by the clients
The precond must not use features hidden from the clients as a
result of export restrictions
Every feature in the precond must be available to every client to
which the routine is available
Every client that is in a position to call the feature will also be
in a position to check for its precond.
No such rule for postconds
It’s not an error for a postcond to refer to secret features.
32
Precondition Availability Rule - cont
-- an invalid class, for illustration only
class SNEAKY feature
tricky is // exports tricky to all clients
require
accredited // keeps accredited secret
do … end
feature {NONE}
accredited: BOOLEAN is do … end
end
Clients have no way of finding out, before a call, whether the
call is indeed correct.
33
Demanding vs Tolerant
Demanding
Usually the right one for modules whose clients are other
software modules
Exception: modules intended for clients whose authors use a
non-OO language or may not understand DBC
Tolerant
Useful for software elements that deal with data coming from
the outside world, such as user input, or sensor data.
34
Class Invariants
Class invariant - a set of assertions, expressing general
consistency constraints that every class instance will satisfy at
all “stable” times:
The state that results from the creation of an object
The states immediately before and after a call
May involve attributes, routines, and both
0 <= count && count <= capacity
empty = (count = 0)
Does not need to be satisfied at all times
35
Invariants and Routine Execution
Execution of a.f (…)
begins by trying to work towards its postcond
destroys the invariant in the process
restores the invariant before termination
Obligation to maintain the invariant applies
only to the body of features exported;
not to a secret feature.
36
Invariant Rule
An assertion I is a correct class invariant for a class if and only
if it meets:
E1: Every creation proc. yields a state satisfying I.
When applied to arguments satisfying its precond in a state
where the attributes have their default values
E2: Every exported routine yields a state satisfying I
When applied to arguments and a state satisfying both I and the
routine’s precondition.
37
Class Invariants and Contracting
Class invariant affects all the contracts between a routine and a
client.
Implicit pre/post-cond of every exported routine (E2).
{INV && pre} body {INV && post}
If you implement the body, the invariant:
Makes your job easier - take this stronger precond for granted at
the start of the routine;
Makes your job harder - ensure that the routine will satisfy the
stronger postcond on termination
38
When Is a Class Correct?
If and only if its implementation is consistent with the
preconds, postconds and invariant.
A class is correct w.r.t. its assertions iff:
For any valid arguments xp to creation procedure p:
{DefaultC && prep(xp)} Bodyp {postp (xp) && INV}
For every exported routine r and any valid args xr:
{prer (xr) && INV} Bodyr {postr (xr) && INV}
Role of creation procedures
They make sure that any instance of the class, when it starts its
life, already satisfies the fundamental rules of its caste — the
class invariant
39
The ADT Connection
A class is an implementation of an ADT
ADT: type, functions, axioms, preconds
Functions: creator, query, command.
Axioms, preconds: semantic properties of functions
ADT properties and class assertions
A precond of ADT function - precond for the routine
An axiom involving a command – postcond
Axioms involving only queries - postcond of function or
invariant.
Axioms involving creators - postcond of creator
40
The ADT Connection - cont
Implementation invariants
Related to representation; meaningless in ADT
Assertions in invariant have no counterparts in ADT.
count_non_negative: 0 <= count
count_bounded: count <= capacity
Class interface is restricted to the features directly deduced
from the ADT’s functions.
41
Loops
To reveal the bug, how many times should the be loop
executed?
a = [1,2,3,4]
sum =0;
while (i>0) { /* i =0, 1, 2, 3…? */
i = i-1;
sum = a [i]; /*oops, should be +=*/
}
The wrong result is given only when the loop is executed more
than once.
42
Loops - cont
Loop coverage for while (test) body requires:
The test be false on its first evaluation so the body is not
executed
The test be true the first time, then false, so the loop body is
executed exactly once
The test be true at least twice, forcing at least two executions of
the loop
There are faults that can be detected only in one of these cases.
Coverage criteria: 0/1/n/Max…
Testing does not assure correctness!
43
Loop Invariants and Variants
Loop trouble
“Off-by-one” errors, performing one iteration too many or too
few.
Improper handling of borderline cases
Infinite looping in some cases.
Getting loops right
loop invariant (assertions)
loop variant (an integer expression)
44
Loop Example: Maximum of an array
45
Loop Example - cont
maxarray (t: ARRAY [INTEGER]): INTEGER is
-- The highest of the values in the entries of t
require t.capacity >= 1
local i: INTEGER
do
from
i := t.lower
Result := t @ lower
until i = t.upper loop
i := i + 1
Result := Result.max (t @ i)
end // t @ i: the element at index i
end // a.max (b): max of {a, b}
46
Loop Example - cont
Loop invariant
at each stage through the loop Result is the maximum of the
current approximation of the array.
Invariant maintenance
First, true after the initialization,
Then, on each iteration, extend the slice by one element, and
update Result if the new value is higher than the previous
maximum
At the end, the approximation covers the entire array
47
Ingredients for a provably correct loop
Postcondition or goal (post): a property that any satisfactory
end state must satisfy.
Result is the maximum value in the array
Invariant (inv): a generalization of the goal
Result is the max in a non-empty array slice beginning at the
lower bound
Initial point (init): satisfying inv
Transformation body: starting from a point in inv but not in
post, yields a point closer to post and still in inv.
Upper bound on the number of applications of body necessary to
bring a point in inv to post
48
Loop Variant
Termination is not difficult to prove for loops with finite
interval (for, do),
For more sophisticated loops, the only universal technique is to
find a variant.
A loop variant is an integer quantity such that
it is always non-negative.
any execution of body decreases the variant.
t.upper – i.
49
Using Assertions
Help in writing correct software
Spelling out the exact requirements on each routine, and the
global properties of classes and loops
Documentation aid
Precond, postcond, and class invariants provide clients with
concise/precise info about the services
Support for testing, debugging, fault tolerance
Need runtime monitoring of assertions
Assertion evaluation rule:
During the process of evaluating an assertion at runtime, routine
calls used by the assertion shall be executed without evaluation
of the associated assertions.
50
Exceptions – When Contract Is Broken
Success and Failure
A routine call succeeds if it terminates its execution in a state
satisfying the routine’s contract.
It fails if it does not succeed.
Exception and Failure
Run-time event that may cause a routine call to fail
Every failure results from an exception, but not every exception
results in failure
A failure of a routine causes an exception in its caller.
A routine call will fail iff an exception occurs and the routine
does not recover from the exception.
51
Sources of Exceptions
Exception may occur during the exec of routine r:
Attempting call a.f and a is void.
Executing an operation that produces an abnormal condition
detected by the hardware or OS.
Calling a routine that fails.
Finding r’s precond (postcond) doesn’t hold on entry (exit)
Finding that class invariant doesn’t hold on entry or exit.
Finding that the invariant of a loop is violated.
Finding that an iteration of a loop’s body does not decrease the
variant.
Finding that its embedded assertion does not hold.
Executing an instruction meant explicitly to trigger an
exception.
52
Disciplined Exception Handling Principle
Retrying
Hopeful strategy
“We have lost a battle, but we have not lost the war”
Battle: the current attempt at executing the routine body
War: the attempt to terminate the call so as to satisfy the
contract
Attempt to change the conditions that lead to the exception and
to exec the routine again from the start
If we succeed, the client will be entirely unaffected, and the
contract is fulfilled.
Read an integer
53
53
Disciplined Exception Handling Principle
Failure (a.k.a. Organized Panic)
Give-up strategy
“Not only have lost the battle, but cannot win the war”
Clean up the environment, terminate the call and report failure
to the caller.
Panic aspect
Making sure the caller gets an exception - the routine has failed
to live up to its contract
Organized aspect
A routine execution may temporarily violate the invariant
Restoring a consistent execution state that satisfies the
invariant.
sqrt
54
54
Call Chain
55
If a routine produces an exception, it may be necessary to go up
the chain until finding a routine equipped to handle the
exception, or stop execution if we reach r0

More Related Content

PPTX
Software construction and development.pptx
PDF
Defencive programming
PPT
PPTX
Ooad presentation
PPT
Reliable and Concurrent Software: SPARK presentation
PPTX
H testing and debugging
PDF
Chapter 2 program-security
PDF
Grounded Pointers
Software construction and development.pptx
Defencive programming
Ooad presentation
Reliable and Concurrent Software: SPARK presentation
H testing and debugging
Chapter 2 program-security
Grounded Pointers

Similar to NDSU CSCI 717Software ConstructionDefensive Programming.docx (20)

PDF
Security overview 2
PDF
Bringing the hacker mindset into requirements and testing by Eapen Thomas and...
PPTX
KYS SSD - SOMMERVILE CH13-SECURE PROGRAMMING.pptx
PPT
Fuzzing101 uvm-reporting-and-mitigation-2011-02-10
PDF
Web Application Penetration Tests - Reporting
DOC
Manual testing interview question by INFOTECH
PPTX
Enterprise Architecture in Practice: from Datastore to APIs and Apps
PDF
Notes how to work with variables, constants and do calculations
PDF
DIG1108 Lesson 7
DOCX
Projec4 Risk Management Plant V3
DOC
Manualtestinginterviewquestionbyinfotech 100901071035-phpapp01
DOC
Manual testing interview questions by infotech
PPT
Quality Assurance in SE lecture week 08 .ppt
PPTX
PPT
Program logic and design
DOCX
27 Introduction Risk management begins with first .docx
DOCX
27 Introduction Risk management begins with first .docx
PPTX
Mark asoi ppt
PPT
Code coverage in theory and in practice form the do178 b perspective
PPT
Code Coverage in Theory and in practice form the DO178B perspective
Security overview 2
Bringing the hacker mindset into requirements and testing by Eapen Thomas and...
KYS SSD - SOMMERVILE CH13-SECURE PROGRAMMING.pptx
Fuzzing101 uvm-reporting-and-mitigation-2011-02-10
Web Application Penetration Tests - Reporting
Manual testing interview question by INFOTECH
Enterprise Architecture in Practice: from Datastore to APIs and Apps
Notes how to work with variables, constants and do calculations
DIG1108 Lesson 7
Projec4 Risk Management Plant V3
Manualtestinginterviewquestionbyinfotech 100901071035-phpapp01
Manual testing interview questions by infotech
Quality Assurance in SE lecture week 08 .ppt
Program logic and design
27 Introduction Risk management begins with first .docx
27 Introduction Risk management begins with first .docx
Mark asoi ppt
Code coverage in theory and in practice form the do178 b perspective
Code Coverage in Theory and in practice form the DO178B perspective

More from vannagoforth (20)

DOCX
1. Primary sources2. Secondary sources3. La Malinche4. Bacon’s.docx
DOCX
1. Prepare an outline, an introduction, and a summary.docx
DOCX
1. Normative moral philosophy typically focuses on the determining t.docx
DOCX
1. Paper should be 5-pages min. + 1 page works cited2. Should have.docx
DOCX
1. Name and describe the three steps of the looking-glass self.2.docx
DOCX
1. Provide an example of a business or specific person(s) that effec.docx
DOCX
1. Mexico and Guatemala. Research the political and economic situati.docx
DOCX
1. Many scholars have set some standards to judge a system for taxat.docx
DOCX
1. List and (in 1-2 sentences) describe the 4 interlocking factors t.docx
DOCX
1. Please explain how the Constitution provides for a system of sepa.docx
DOCX
1. Please watch the following The Diving Bell & The Butterfly, Amel.docx
DOCX
1. Most sociologists interpret social life from one of the three maj.docx
DOCX
1. Members of one species cannot successfully interbreed and produc.docx
DOCX
1. Of the three chemical bonds discussed in class, which of them is .docx
DOCX
1. Look at your diagrams for hydrogen, lithium, and sodium. What do .docx
DOCX
1. Name the following molecules2. Sketch the following molecules.docx
DOCX
1. List the horizontal and vertical levels of systems that exist in .docx
DOCX
1. Kemal Ataturk carried out policies that distanced the new Turkish.docx
DOCX
1. If we consider a gallon of gas as having 100 units of energy, and.docx
DOCX
1. In 200-250 words, analyze the basic issues of human biology as th.docx
1. Primary sources2. Secondary sources3. La Malinche4. Bacon’s.docx
1. Prepare an outline, an introduction, and a summary.docx
1. Normative moral philosophy typically focuses on the determining t.docx
1. Paper should be 5-pages min. + 1 page works cited2. Should have.docx
1. Name and describe the three steps of the looking-glass self.2.docx
1. Provide an example of a business or specific person(s) that effec.docx
1. Mexico and Guatemala. Research the political and economic situati.docx
1. Many scholars have set some standards to judge a system for taxat.docx
1. List and (in 1-2 sentences) describe the 4 interlocking factors t.docx
1. Please explain how the Constitution provides for a system of sepa.docx
1. Please watch the following The Diving Bell & The Butterfly, Amel.docx
1. Most sociologists interpret social life from one of the three maj.docx
1. Members of one species cannot successfully interbreed and produc.docx
1. Of the three chemical bonds discussed in class, which of them is .docx
1. Look at your diagrams for hydrogen, lithium, and sodium. What do .docx
1. Name the following molecules2. Sketch the following molecules.docx
1. List the horizontal and vertical levels of systems that exist in .docx
1. Kemal Ataturk carried out policies that distanced the new Turkish.docx
1. If we consider a gallon of gas as having 100 units of energy, and.docx
1. In 200-250 words, analyze the basic issues of human biology as th.docx

Recently uploaded (20)

PPTX
Institutional Correction lecture only . . .
PDF
Classroom Observation Tools for Teachers
PDF
RMMM.pdf make it easy to upload and study
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Computing-Curriculum for Schools in Ghana
PPTX
master seminar digital applications in india
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Complications of Minimal Access Surgery at WLH
Institutional Correction lecture only . . .
Classroom Observation Tools for Teachers
RMMM.pdf make it easy to upload and study
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Anesthesia in Laparoscopic Surgery in India
Supply Chain Operations Speaking Notes -ICLT Program
VCE English Exam - Section C Student Revision Booklet
O5-L3 Freight Transport Ops (International) V1.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Computing-Curriculum for Schools in Ghana
master seminar digital applications in india
102 student loan defaulters named and shamed – Is someone you know on the list?
Module 4: Burden of Disease Tutorial Slides S2 2025
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Insiders guide to clinical Medicine.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
O7-L3 Supply Chain Operations - ICLT Program
Complications of Minimal Access Surgery at WLH

NDSU CSCI 717Software ConstructionDefensive Programming.docx

  • 1. NDSU CSCI 717 Software Construction Defensive Programming Textbook Steve McConnell. Code Complete: A Practical Handbook of Software Construction. 2nd Edition. Microsoft Press, 2004. Chapter 8. 2 Outline Protecting from Invalid Inputs Using Assertions Error-Handling Techniques Using Exceptions Barricade/Firewall Your Program Debugging Aids Be Defensive about Defensive Programming 3 Protecting from Invalid Inputs Garbage in, garbage out? Mark of sloppy nonsecure program
  • 2. Garbage in, nothing/error message out No garbage allowed in Defensive programming If a routine is passed bad data, it won’t be hurt, even if the bad data is another routine’s fault. Check values of all data from external sources Sources: file, user, network Allowable range: String vs security problem Check values of all routine input parameters Decide how to handle bad inputs 4 Assertions To document assumptions made in the code and to flush out unexpected conditions An input/output parameter in its expected range A file/stream is open (or closed) when a routine begins (or ends) executing A file/stream is at the beginning A file/stream is open for read-only, write-only, etc. An input-only variable is not changed A pointer is non-null A container is empty (or full) when a routine begins (or ends) executing Match two results 5 Assertion Mechanism Java assertions Assert denominator!=0 : “denominator is 0” Define your own #define ASSERT(condition, message) { if (!(condition)) {
  • 3. LogError(“Assertion failed: ”, #condition, message); exit(EXIT_FAILURE); } } 6 Using Assertions: Guidelines Use error-handling for conditions you expect to occur; use assertions for condition that should never occur Error handling typically checks for bad input Assertions check for bugs in the code Avoid putting executable code into assertions The compiler will eliminate the code when the assertions are turned off Use assertions to document/verify pre/postconds For highly robust code, assert and then handle the error anyway. E.g. change an invalid input to the closest legal value 7 Error-Handling Techniques Return a neutral value (known to be harmless) Examples: 0, empty string, default color Substitute the next place of valid data Encounter a corrupted record when reading from a DB Return the same answer as the previous time Thermometer-reading code does not get a reading one time Substitute the closest legal value Log a warning message to a file Return an error code 8 Error-Handling Techniques Call an error processing routine/object
  • 4. Centralize error handling in a global routine/object Display an error message wherever the error is encountered Handle the error in whatever way works best locally Individual developers have the flexibility Risky: spread UI code throughout the system Shut down Safety critical applications 9 Using Exceptions: Suggestions Use exceptions to notify other parts about errors that should not be ignored Throw an exception only for conditions that are truly exceptional Cannot be addressed by other coding practices Don’t throw an uncaught exception if you can handle the error locally Avoid throwing exceptions in constructors /destructors unless you catch them in the same place The rule for how exceptions are processed become very complicated C++: destructors are not called unless an object is fully constructed 10 Using Exceptions: Suggestions - cont Throw exceptions at the right level of abstraction The exceptions thrown are part of the interface Class Employee { public TaxId GetTaxId() throws EOFException public TaxId GetTaxId() throws EmployeeDataNotAvailable } Include in the exception message all info that led to the exception
  • 5. Avoid empty catch blocks Know the exceptions your library code throws Consider building a centralized exception reporter Standardize your project’s use of exceptions Consider alternatives to exceptions 11 Barricade/Firewall Your Program A building’s firewall prevents fire from spreading from one part of the building to another part Barricade your program to contain the damage caused by errors Designate certain interfaces as boundaries to safe areas Check data crossing the boundaries of a safe area for validity, and respond sensibly if the data is invalid Class Level Public methods assume the data is unsafe Private methods can assume the data is safe 12 Debugging Aids Introduce debugging aids early Don’t automatically apply production constraints to the development version Differences: speed, resource, etc Use offensive programming Exceptional cases should be handled in a way that makes them obvious during development and recoverable when production code is running. (Howard & Leblanc 2003, Writing secure code) Default clause of case statement Development - warning: “hey, another case here! Fix it” Production - something more graceful, e.g. error-log Plan to remove debugging aids 13
  • 6. Programming Offensively Make sure asserts abort the program Don’t allow programmers to get into the habit of just hitting the Enter key to bypass a known problem Completely fill any memory allocated to detect memory allocation errors Completely fill any files/streams allocated to flush out any file- format errors Be sure the code of default/else clause fails hard (aborts the program) or is o.w. impossible to overlook Fill an object with junk data just before it is deleted … 14 Be Defensive about Defensive Prog. Think about where you need to be defensive. Set you defensive programming priorities accordingly. 15 NDSU CSCI 717 Software Construction Design By Contract
  • 7. Textbook Bertrand Meyer. Object-Oriented Software Construction, 2nd Edition, Prentice-Hall PTR, 1997. Chapters 11 and 12. 2 Outline Correctness Formula Assertions and Contracts Class Invariants When Is a Class Correct? ADT Connection Loop Invariants and Variants Using Assertions Exception Handling 3 Is x := y + 1 Correct? “Make sure that x and y have different values” “Make sure that x has a negative value” Correctness is a relative notion. Need to get not only the program but also a precise description of what it is supposed to do Specification! 4 Reliability: Correctness & Robustness Correctness The ability of software products to perform their exact tasks, as
  • 8. defined by their specification Robustness The ability of software systems to react appropriately to abnormal conditions Need a mechanism for expressing and validating correctness arguments. 5 Reliability via Design By Contract Viewing the relationship between a class and its clients as a formal agreement Expressing each party’s rights and obligations. Through a precise definition of every module’s claims and responsibilities, we hope to attain a significant degree of trust in large systems. 6 Correctness Formula {P} A {Q} – a.k.a. Hoare Triples A – operation/routine P – precondition Q – postcondition “Any execution of A, starting in a state where P holds, will terminate in a state where Q holds.” 7 Correctness Formula: Example {x >= 9} x := x + 5 {x >= 13} Given {x >= 9}, the most interesting postcond?
  • 9. {x >= 14} Strongest possible Given {x>=13}, the most interesting precond? {x>=8} Weakest possible 8 Weak and Strong Conditions P1 is stronger than P2 if P1 implies P2 (P1≠P2) i.e. P2 is weaker than P1 legitimate to speak of True as the weakest and False as the strongest of all possible assertions. Every proposition implies True False implies every proposition 9 {P}A{Q}: Employee Perspective Job Ad: “We are looking for someone whose work will be to start from initial situations as characterized by P, and deliver results as defined by Q”. Assume a friend is looking for a job and comes across several such ads, all with similar salary and benefits, but differing by their Ps and Qs. Lazy friend wants the easiest possible job: sinecure Recommend for P/Q: choose a job with a weaker or stronger precondition/postcondition? 10 {P}A{Q}: Employee Perspective-cont
  • 10. Sinecure 1: {False} A {…} The stronger the P, the easier for the employee Only have to deal with a more limited set of situations False, the strongest possible, is never satisfied Any request to execute A will be incorrect, the fault lies not with A but with the requester Who did not observe the required precondition Whatever A does or does not do may be useless, but A is always correct! Do you want/know any of such jobs? 11 {P}A{Q}: Employee Perspective-cont “Obvious — it is the only job where the customer is always wrong” why a famous police chief had chosen his career. 12 {P}A{Q}: Employee Perspective - cont Sinecure 2: {…} A {True} A strong postcond is bad news - you have to deliver more results. The weaker the Q, the better for the employee. True, the weakest possible, is satisfied by all states Sinecure1 and Sinecure2, which is better? 13 {P}A{Q}: Employee Perspective - cont With Sinecure1, A is always correct! No states satisfy P, so it does not matter what A does, even if
  • 11. A’s execution would go into an infinite loop or crash the computer. With Sinecure 2, there must be a final state. The final state does not need to satisfy any specific properties, but it must exist. “You need to do nothing, but must do it in finite time” Sinecure 2 is only the “second best” job! 14 {P}A{Q}: Employer Perspective Everything is reversed. A weaker precond is good news: a job that handles a broader set of input cases A stronger postcond means more significant results For contracts between clients and suppliers, a benefit for one is an obligation for the other! 15 Introducing Assertions into Programs Assertion An expression stating a property that some entities may satisfy at certain stages of program execution. Notation: predicates+ extensions ; and : between label and component n > 0 ; x /= Void Positive: n > 0 Not_void: x /= Void
  • 12. 16 Preconditions and Postconditions Routines are characterized by strong semantic properties, independent of specific representation remove and item are only applicable if the number of elements is not zero. put increases the number of elements by one; remove decreases it by one. Require: precondition stating the properties that must hold whenever the routine is called Ensure: postcondition stating the properties that the routine guarantees when it returns. 17 Stack class STACK1 [G] feature -- Access count: INTEGER is -- Number of stack elements item: G is -- Top element require // may not be applied to an empty stack not empty do … end 18 Stack: status report & element change feature -- Status report empty: BOOLEAN is
  • 13. -- Is stack empty? do … end full: BOOLEAN is -- Is stack representation full? do … end feature -- Element change put, move (next two slides) 19 Stack: put put (x: G) is -- Add x on top. Require // put may not be called not full do … ensure not empty // the stack may not be empty item = x // its top is the element just pushed count = old count + 1 // count increased by one end 20 Stack: remove remove is -- Remove top element. require // may not be applied to an empty stack not empty do … ensure
  • 14. not full // the stack may not be full count = old count – 1 // count decreased by 1 end 21 Contracting for Software Reliability Contract require pre and ensure post with a routine r A pre/postcond pair for a routine is the contract that the routine (supplier) defines for its callers (clients) Rights and Obligations “If you promise to call r with precond satisfied then I, in return, promise to deliver a final state in which postcond is satisfied.” The precond is an obligation for the client and a benefit for the supplier. The postcond is a benefit for the client and an obligation for the supplier. 22 Obligations and Benefits: StackputObligationsBenefitsClient (Satisfy precondition:) Only call put (x) on a non-full stack. (From postcondition:) Get stack updated: not empty, x on top (item yields x, count increased by 1).Supplier(Satisfy postcondition:) Update stack to have x on top (item yields x), count increased by 1, not empty.(From precondition:) Simpler processing thanks to the assumption that stack is not full. 23
  • 15. Non-Redundancy Principle Under no circumstances shall the body of a routine ever test for its precondition. A precondition is a benefit for the supplier; If the call does not satisfy the precond, the routine is not bound by the postcond - it may do what it pleases Advantages Simplicity “The more we write, the more we will have to write”. Performance Zen–style paradox – “get more reliability the best policy is often to check less” Reverse of defensive programming A redundant check might not help,but at least it will not hurt 24 Understanding Assertions Assertions are no input checking mechanism Concern: software-to-software communication, not software-to- human or software-to-outside-world. In obtaining information from the outside you cannot rely on preconditions - use input validation or “filter” Assertions are not control structures Assertions express correctness conditions. If sqrt handles negative arguments a certain way, and non- negatives another way, a require clause is not what you need. 25 Who’s Fault? Programmer A double x = -1; double y = sqrt(x); assert abs(y*y-x)<eps // failure
  • 16. 26 Programmer B double sqrt(double x) { //… } Assertion Violation Rules A run-time assertion violation is the manifestation of a bug. A precondition violation - a bug in the client The client did not observe its part of the deal. A postcondition violation - a bug in the supplier. The supplier was not able to fulfill its contract. 27 Precondition Design Demanding Assign the responsibility to clients - the condition will appear as part of the routine’s precondition An experienced contractor expects his clients to “do their homework” before calling on him; He has no trouble finding business, and will reject requests that appear too broad or unreasonable. Tolerant The condition will appear in an if- then or an equivalent control structure in the routine. A freshly established consulting practice, whose owner is so desperate for business He will take anything 28
  • 17. 28 Tolerant Version of remove remove is -- Remove top element // no precondition do if empty then print ("Error: attempt to pop an empty stack") else count := count – 1 end end 29 Demanding in Design by Contract Demanding does not mean to produce routines that assign all things to all clients. Insists that each routine Do a well-defined job and do it well Correctly, efficiently, generally enough to be reusable by many clients Specify clearly what cases it cannot handle. Only applicable if preconds remain reasonable O.W. require False makes any routine body correct 30 Reasonable Precondition Principle Every routine precond in a “demanding” design approach must satisfy these requirements: The precond appears in the official documentation distributed to authors of client modules. It is possible to justify the need for the precondition in terms of
  • 18. the specification only. Examples remove’s precond: not empty sqrt’s precond: x>0 Logical requirements, not for supplier’s implementation convenience 31 Precondition Availability Rule To be satisfiable by the clients The precond must not use features hidden from the clients as a result of export restrictions Every feature in the precond must be available to every client to which the routine is available Every client that is in a position to call the feature will also be in a position to check for its precond. No such rule for postconds It’s not an error for a postcond to refer to secret features. 32 Precondition Availability Rule - cont -- an invalid class, for illustration only class SNEAKY feature tricky is // exports tricky to all clients require accredited // keeps accredited secret do … end feature {NONE} accredited: BOOLEAN is do … end end Clients have no way of finding out, before a call, whether the call is indeed correct. 33
  • 19. Demanding vs Tolerant Demanding Usually the right one for modules whose clients are other software modules Exception: modules intended for clients whose authors use a non-OO language or may not understand DBC Tolerant Useful for software elements that deal with data coming from the outside world, such as user input, or sensor data. 34 Class Invariants Class invariant - a set of assertions, expressing general consistency constraints that every class instance will satisfy at all “stable” times: The state that results from the creation of an object The states immediately before and after a call May involve attributes, routines, and both 0 <= count && count <= capacity empty = (count = 0) Does not need to be satisfied at all times 35 Invariants and Routine Execution Execution of a.f (…) begins by trying to work towards its postcond destroys the invariant in the process restores the invariant before termination Obligation to maintain the invariant applies
  • 20. only to the body of features exported; not to a secret feature. 36 Invariant Rule An assertion I is a correct class invariant for a class if and only if it meets: E1: Every creation proc. yields a state satisfying I. When applied to arguments satisfying its precond in a state where the attributes have their default values E2: Every exported routine yields a state satisfying I When applied to arguments and a state satisfying both I and the routine’s precondition. 37 Class Invariants and Contracting Class invariant affects all the contracts between a routine and a client. Implicit pre/post-cond of every exported routine (E2). {INV && pre} body {INV && post} If you implement the body, the invariant: Makes your job easier - take this stronger precond for granted at the start of the routine; Makes your job harder - ensure that the routine will satisfy the stronger postcond on termination 38 When Is a Class Correct? If and only if its implementation is consistent with the preconds, postconds and invariant. A class is correct w.r.t. its assertions iff: For any valid arguments xp to creation procedure p:
  • 21. {DefaultC && prep(xp)} Bodyp {postp (xp) && INV} For every exported routine r and any valid args xr: {prer (xr) && INV} Bodyr {postr (xr) && INV} Role of creation procedures They make sure that any instance of the class, when it starts its life, already satisfies the fundamental rules of its caste — the class invariant 39 The ADT Connection A class is an implementation of an ADT ADT: type, functions, axioms, preconds Functions: creator, query, command. Axioms, preconds: semantic properties of functions ADT properties and class assertions A precond of ADT function - precond for the routine An axiom involving a command – postcond Axioms involving only queries - postcond of function or invariant. Axioms involving creators - postcond of creator 40 The ADT Connection - cont Implementation invariants Related to representation; meaningless in ADT Assertions in invariant have no counterparts in ADT. count_non_negative: 0 <= count count_bounded: count <= capacity Class interface is restricted to the features directly deduced from the ADT’s functions. 41
  • 22. Loops To reveal the bug, how many times should the be loop executed? a = [1,2,3,4] sum =0; while (i>0) { /* i =0, 1, 2, 3…? */ i = i-1; sum = a [i]; /*oops, should be +=*/ } The wrong result is given only when the loop is executed more than once. 42 Loops - cont Loop coverage for while (test) body requires: The test be false on its first evaluation so the body is not executed The test be true the first time, then false, so the loop body is executed exactly once The test be true at least twice, forcing at least two executions of the loop There are faults that can be detected only in one of these cases. Coverage criteria: 0/1/n/Max… Testing does not assure correctness! 43 Loop Invariants and Variants Loop trouble “Off-by-one” errors, performing one iteration too many or too few. Improper handling of borderline cases Infinite looping in some cases.
  • 23. Getting loops right loop invariant (assertions) loop variant (an integer expression) 44 Loop Example: Maximum of an array 45 Loop Example - cont maxarray (t: ARRAY [INTEGER]): INTEGER is -- The highest of the values in the entries of t require t.capacity >= 1 local i: INTEGER do from i := t.lower Result := t @ lower until i = t.upper loop i := i + 1 Result := Result.max (t @ i) end // t @ i: the element at index i end // a.max (b): max of {a, b} 46 Loop Example - cont Loop invariant at each stage through the loop Result is the maximum of the current approximation of the array. Invariant maintenance First, true after the initialization, Then, on each iteration, extend the slice by one element, and
  • 24. update Result if the new value is higher than the previous maximum At the end, the approximation covers the entire array 47 Ingredients for a provably correct loop Postcondition or goal (post): a property that any satisfactory end state must satisfy. Result is the maximum value in the array Invariant (inv): a generalization of the goal Result is the max in a non-empty array slice beginning at the lower bound Initial point (init): satisfying inv Transformation body: starting from a point in inv but not in post, yields a point closer to post and still in inv. Upper bound on the number of applications of body necessary to bring a point in inv to post 48 Loop Variant Termination is not difficult to prove for loops with finite interval (for, do), For more sophisticated loops, the only universal technique is to find a variant. A loop variant is an integer quantity such that it is always non-negative. any execution of body decreases the variant. t.upper – i. 49 Using Assertions
  • 25. Help in writing correct software Spelling out the exact requirements on each routine, and the global properties of classes and loops Documentation aid Precond, postcond, and class invariants provide clients with concise/precise info about the services Support for testing, debugging, fault tolerance Need runtime monitoring of assertions Assertion evaluation rule: During the process of evaluating an assertion at runtime, routine calls used by the assertion shall be executed without evaluation of the associated assertions. 50 Exceptions – When Contract Is Broken Success and Failure A routine call succeeds if it terminates its execution in a state satisfying the routine’s contract. It fails if it does not succeed. Exception and Failure Run-time event that may cause a routine call to fail Every failure results from an exception, but not every exception results in failure A failure of a routine causes an exception in its caller. A routine call will fail iff an exception occurs and the routine does not recover from the exception. 51 Sources of Exceptions Exception may occur during the exec of routine r: Attempting call a.f and a is void. Executing an operation that produces an abnormal condition detected by the hardware or OS. Calling a routine that fails.
  • 26. Finding r’s precond (postcond) doesn’t hold on entry (exit) Finding that class invariant doesn’t hold on entry or exit. Finding that the invariant of a loop is violated. Finding that an iteration of a loop’s body does not decrease the variant. Finding that its embedded assertion does not hold. Executing an instruction meant explicitly to trigger an exception. 52 Disciplined Exception Handling Principle Retrying Hopeful strategy “We have lost a battle, but we have not lost the war” Battle: the current attempt at executing the routine body War: the attempt to terminate the call so as to satisfy the contract Attempt to change the conditions that lead to the exception and to exec the routine again from the start If we succeed, the client will be entirely unaffected, and the contract is fulfilled. Read an integer 53 53 Disciplined Exception Handling Principle Failure (a.k.a. Organized Panic) Give-up strategy “Not only have lost the battle, but cannot win the war” Clean up the environment, terminate the call and report failure to the caller.
  • 27. Panic aspect Making sure the caller gets an exception - the routine has failed to live up to its contract Organized aspect A routine execution may temporarily violate the invariant Restoring a consistent execution state that satisfies the invariant. sqrt 54 54 Call Chain 55 If a routine produces an exception, it may be necessary to go up the chain until finding a routine equipped to handle the exception, or stop execution if we reach r0