SlideShare a Scribd company logo
Defensive Programming

Code Complete
Author : Steven C. McConnell.

Prof. Asha N

1
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

2
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

3
Contd….


three general ways to handle garbage in
1.

2.

3.

Check the values of all data from external
sources
Check the values of all routine input
parameters
Decide how to handle bad inputs

Prof. Asha N

4
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

5
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: %sn", 
#condition, message ); 
exit( EXIT_FAILURE ); 
}
}

Prof. Asha N

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 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

7
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

8
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

9
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

10
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

11
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

12
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

13
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

14
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

Prof. Asha N

15

More Related Content

PPT
Defensive programming
PPTX
What is Exception Handling?
PPT
Exception handler
PPTX
Presentation1
PPT
Exception Handling Mechanism in .NET CLR
PPT
Week7 exception handling
PPT
Understanding Exception Handling in .Net
PDF
Programming katas for Software Testers - CounterStrings
Defensive programming
What is Exception Handling?
Exception handler
Presentation1
Exception Handling Mechanism in .NET CLR
Week7 exception handling
Understanding Exception Handling in .Net
Programming katas for Software Testers - CounterStrings

What's hot (20)

PPT
C# Exceptions Handling
PPT
Exception handling in c++ by manoj vasava
PDF
Exception handling
ODP
PPTX
Exception handling in asp.net
PPTX
Exception handling
PPTX
C++ ala
PPTX
Chapter 13 exceptional handling
PPTX
Exception handling in c
PDF
14 exception handling
PPTX
Exception handling in ASP .NET
PPTX
Exception handling in JAVA
PDF
Python exception handling
PPTX
PDF
Best Practices in Exception Handling
PPSX
Exception Handling
PPTX
Exception Handling in C++
PPTX
Exception handling in c++
PPT
Exception handling
PPS
Exception handling in c programming
C# Exceptions Handling
Exception handling in c++ by manoj vasava
Exception handling
Exception handling in asp.net
Exception handling
C++ ala
Chapter 13 exceptional handling
Exception handling in c
14 exception handling
Exception handling in ASP .NET
Exception handling in JAVA
Python exception handling
Best Practices in Exception Handling
Exception Handling
Exception Handling in C++
Exception handling in c++
Exception handling
Exception handling in c programming
Ad

Viewers also liked (19)

PDF
高品質軟體的基本動作 101 + 102 for NUU
PPT
A Guideline to Test Your Own Code - Developer Testing
PPT
代码大全(内训)
PPTX
程序员实践之路
PDF
Design in construction
PDF
程序员发展漫谈
PDF
Coding Style
PDF
Design in construction
PDF
MOST_OpenFoundry_version control system_Git
PPTX
Java scriptcore brief introduction
PPTX
Variables
PDF
Code tuning techniques
PDF
Integration
PDF
Code tuning strategies
PDF
高品質軟體的基本動作 101 for NTHU
PPT
Code Tuning
PDF
The pseudocode
PPT
Rm 1 Intro Types Research Process
高品質軟體的基本動作 101 + 102 for NUU
A Guideline to Test Your Own Code - Developer Testing
代码大全(内训)
程序员实践之路
Design in construction
程序员发展漫谈
Coding Style
Design in construction
MOST_OpenFoundry_version control system_Git
Java scriptcore brief introduction
Variables
Code tuning techniques
Integration
Code tuning strategies
高品質軟體的基本動作 101 for NTHU
Code Tuning
The pseudocode
Rm 1 Intro Types Research Process
Ad

Similar to Defencive programming (20)

PPTX
Software construction and development.pptx
PPTX
1606125427-week8.pptx
DOCX
NDSU CSCI 717Software ConstructionDefensive Programming.docx
PPTX
DefensiveProgramming (1).pptx
PPTX
Lecture 20-21
PDF
javase-1.4.2-docs-guide-lang-assert
PDF
Top 10 Bad Coding Practices Lead to Security Problems
PPTX
SUBHASH.pptx
PPTX
The Pragmatic Programmer
PPT
12slide.ppt
PDF
A exception ekon16
PPTX
Fundamental Principles of Software Development
PPTX
Exception handling
PPT
Assertions a Decade Later (invited talk at ICSE 2002)
PPTX
Chapter_4_WP_with_C#_Exception_Handling_student_1.0.pptx
PPT
exception-handling-in-java.ppt
PPT
JP ASSIGNMENT SERIES PPT.ppt
PPTX
Pi j4.2 software-reliability
PPTX
Lecture 3.1.1 Try Throw Catch.pptx
PPT
Exception handling
Software construction and development.pptx
1606125427-week8.pptx
NDSU CSCI 717Software ConstructionDefensive Programming.docx
DefensiveProgramming (1).pptx
Lecture 20-21
javase-1.4.2-docs-guide-lang-assert
Top 10 Bad Coding Practices Lead to Security Problems
SUBHASH.pptx
The Pragmatic Programmer
12slide.ppt
A exception ekon16
Fundamental Principles of Software Development
Exception handling
Assertions a Decade Later (invited talk at ICSE 2002)
Chapter_4_WP_with_C#_Exception_Handling_student_1.0.pptx
exception-handling-in-java.ppt
JP ASSIGNMENT SERIES PPT.ppt
Pi j4.2 software-reliability
Lecture 3.1.1 Try Throw Catch.pptx
Exception handling

Recently uploaded (20)

PPTX
Institutional Correction lecture only . . .
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Pre independence Education in Inndia.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Classroom Observation Tools for Teachers
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
master seminar digital applications in india
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
01-Introduction-to-Information-Management.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
RMMM.pdf make it easy to upload and study
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Institutional Correction lecture only . . .
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Pre independence Education in Inndia.pdf
VCE English Exam - Section C Student Revision Booklet
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Classroom Observation Tools for Teachers
O5-L3 Freight Transport Ops (International) V1.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
master seminar digital applications in india
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
01-Introduction-to-Information-Management.pdf
O7-L3 Supply Chain Operations - ICLT Program
PPH.pptx obstetrics and gynecology in nursing
RMMM.pdf make it easy to upload and study
Supply Chain Operations Speaking Notes -ICLT Program
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Complications of Minimal Access Surgery at WLH
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx

Defencive programming

  • 1. Defensive Programming Code Complete Author : Steven C. McConnell. Prof. Asha N 1
  • 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 2
  • 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 3
  • 4. Contd….  three general ways to handle garbage in 1. 2. 3. Check the values of all data from external sources Check the values of all routine input parameters Decide how to handle bad inputs Prof. Asha N 4
  • 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 5
  • 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: %sn", #condition, message ); exit( EXIT_FAILURE ); } } Prof. Asha N 6
  • 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 7
  • 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 8
  • 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 9
  • 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 10
  • 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 11
  • 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 12
  • 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 13
  • 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 14
  • 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 Prof. Asha N 15