SlideShare une entreprise Scribd logo
1  sur  15
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Tendances (20)

C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasava
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
Exception handling
Exception handlingException handling
Exception handling
 
C++ ala
C++ alaC++ ala
C++ ala
 
Chapter 13 exceptional handling
Chapter 13 exceptional handlingChapter 13 exceptional handling
Chapter 13 exceptional handling
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in c
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
43c
43c43c
43c
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in c programming
Exception handling in c programmingException handling in c programming
Exception handling in c programming
 

En vedette

高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUU高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUUSu Jan
 
A Guideline to Test Your Own Code - Developer Testing
A Guideline to Test Your Own Code - Developer TestingA Guideline to Test Your Own Code - Developer Testing
A Guideline to Test Your Own Code - Developer TestingFolio3 Software
 
代码大全(内训)
代码大全(内训)代码大全(内训)
代码大全(内训)Horky Chen
 
程序员实践之路
程序员实践之路程序员实践之路
程序员实践之路Horky Chen
 
Design in construction
Design in constructionDesign in construction
Design in constructionAsha Sari
 
程序员发展漫谈
程序员发展漫谈程序员发展漫谈
程序员发展漫谈Horky Chen
 
Design in construction
Design in constructionDesign in construction
Design in constructionAsha Sari
 
MOST_OpenFoundry_version control system_Git
MOST_OpenFoundry_version control system_GitMOST_OpenFoundry_version control system_Git
MOST_OpenFoundry_version control system_GitSu Jan
 
Java scriptcore brief introduction
Java scriptcore brief introductionJava scriptcore brief introduction
Java scriptcore brief introductionHorky Chen
 
Code tuning techniques
Code tuning techniquesCode tuning techniques
Code tuning techniquesAsha Sari
 
Code tuning strategies
Code tuning strategiesCode tuning strategies
Code tuning strategiesAsha Sari
 
高品質軟體的基本動作 101 for NTHU
高品質軟體的基本動作 101 for NTHU高品質軟體的基本動作 101 for NTHU
高品質軟體的基本動作 101 for NTHUSu Jan
 
Code Tuning
Code TuningCode Tuning
Code Tuningbgtraghu
 
The pseudocode
The pseudocodeThe pseudocode
The pseudocodeAsha Sari
 
Rm 1 Intro Types Research Process
Rm   1   Intro Types   Research ProcessRm   1   Intro Types   Research Process
Rm 1 Intro Types Research Processitsvineeth209
 

En vedette (19)

高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUU高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUU
 
A Guideline to Test Your Own Code - Developer Testing
A Guideline to Test Your Own Code - Developer TestingA Guideline to Test Your Own Code - Developer Testing
A Guideline to Test Your Own Code - Developer Testing
 
代码大全(内训)
代码大全(内训)代码大全(内训)
代码大全(内训)
 
程序员实践之路
程序员实践之路程序员实践之路
程序员实践之路
 
Design in construction
Design in constructionDesign in construction
Design in construction
 
程序员发展漫谈
程序员发展漫谈程序员发展漫谈
程序员发展漫谈
 
Coding Style
Coding StyleCoding Style
Coding Style
 
Design in construction
Design in constructionDesign in construction
Design in construction
 
MOST_OpenFoundry_version control system_Git
MOST_OpenFoundry_version control system_GitMOST_OpenFoundry_version control system_Git
MOST_OpenFoundry_version control system_Git
 
Java scriptcore brief introduction
Java scriptcore brief introductionJava scriptcore brief introduction
Java scriptcore brief introduction
 
Variables
VariablesVariables
Variables
 
Code tuning techniques
Code tuning techniquesCode tuning techniques
Code tuning techniques
 
Integration
IntegrationIntegration
Integration
 
Code tuning strategies
Code tuning strategiesCode tuning strategies
Code tuning strategies
 
高品質軟體的基本動作 101 for NTHU
高品質軟體的基本動作 101 for NTHU高品質軟體的基本動作 101 for NTHU
高品質軟體的基本動作 101 for NTHU
 
Code Tuning
Code TuningCode Tuning
Code Tuning
 
Code Complete
Code CompleteCode Complete
Code Complete
 
The pseudocode
The pseudocodeThe pseudocode
The pseudocode
 
Rm 1 Intro Types Research Process
Rm   1   Intro Types   Research ProcessRm   1   Intro Types   Research Process
Rm 1 Intro Types Research Process
 

Similaire à Defencive programming

NDSU CSCI 717Software ConstructionDefensive Programming.docx
NDSU CSCI 717Software ConstructionDefensive Programming.docxNDSU CSCI 717Software ConstructionDefensive Programming.docx
NDSU CSCI 717Software ConstructionDefensive Programming.docxvannagoforth
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindPVS-Studio
 
Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...PVS-Studio
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 
Perfomatix - NodeJS Coding Standards
Perfomatix - NodeJS Coding StandardsPerfomatix - NodeJS Coding Standards
Perfomatix - NodeJS Coding StandardsPerfomatix Solutions
 
CLR Exception Handing And Memory Management
CLR Exception Handing And Memory ManagementCLR Exception Handing And Memory Management
CLR Exception Handing And Memory ManagementShiny Zhu
 
KYS SSD - SOMMERVILE CH13-SECURE PROGRAMMING.pptx
KYS SSD - SOMMERVILE CH13-SECURE PROGRAMMING.pptxKYS SSD - SOMMERVILE CH13-SECURE PROGRAMMING.pptx
KYS SSD - SOMMERVILE CH13-SECURE PROGRAMMING.pptxAniSyafrina1
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling ConceptsVicter Paul
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Perfomatix - Java Coding Standards
Perfomatix - Java Coding StandardsPerfomatix - Java Coding Standards
Perfomatix - Java Coding StandardsPerfomatix Solutions
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8Vince Vo
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summaryEduardo Bergavera
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event HandlingJava Programming
 
Fuzzing101 uvm-reporting-and-mitigation-2011-02-10
Fuzzing101 uvm-reporting-and-mitigation-2011-02-10Fuzzing101 uvm-reporting-and-mitigation-2011-02-10
Fuzzing101 uvm-reporting-and-mitigation-2011-02-10Codenomicon
 

Similaire à Defencive programming (20)

NDSU CSCI 717Software ConstructionDefensive Programming.docx
NDSU CSCI 717Software ConstructionDefensive Programming.docxNDSU CSCI 717Software ConstructionDefensive Programming.docx
NDSU CSCI 717Software ConstructionDefensive Programming.docx
 
SUBHASH.pptx
SUBHASH.pptxSUBHASH.pptx
SUBHASH.pptx
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
 
Exception handling
Exception handlingException handling
Exception handling
 
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
 
Exception handling
Exception handlingException handling
Exception handling
 
Perfomatix - NodeJS Coding Standards
Perfomatix - NodeJS Coding StandardsPerfomatix - NodeJS Coding Standards
Perfomatix - NodeJS Coding Standards
 
CLR Exception Handing And Memory Management
CLR Exception Handing And Memory ManagementCLR Exception Handing And Memory Management
CLR Exception Handing And Memory Management
 
KYS SSD - SOMMERVILE CH13-SECURE PROGRAMMING.pptx
KYS SSD - SOMMERVILE CH13-SECURE PROGRAMMING.pptxKYS SSD - SOMMERVILE CH13-SECURE PROGRAMMING.pptx
KYS SSD - SOMMERVILE CH13-SECURE PROGRAMMING.pptx
 
Chapter 2 program-security
Chapter 2 program-securityChapter 2 program-security
Chapter 2 program-security
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Perfomatix - Java Coding Standards
Perfomatix - Java Coding StandardsPerfomatix - Java Coding Standards
Perfomatix - Java Coding Standards
 
$Cash
$Cash$Cash
$Cash
 
$Cash
$Cash$Cash
$Cash
 
6-Error Handling.pptx
6-Error Handling.pptx6-Error Handling.pptx
6-Error Handling.pptx
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event Handling
 
Fuzzing101 uvm-reporting-and-mitigation-2011-02-10
Fuzzing101 uvm-reporting-and-mitigation-2011-02-10Fuzzing101 uvm-reporting-and-mitigation-2011-02-10
Fuzzing101 uvm-reporting-and-mitigation-2011-02-10
 

Dernier

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 

Dernier (20)

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 

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