SlideShare a Scribd company logo
1 of 12
Defensive Programming
Defensive Programming
• Good programming practices that protect you
from your own programming mistakes, as well
as those of others
– Assertions
– Parameter Checking
Assertions
• As we program, we make many assumptions about
the state of the program at each point in the code
– A variable's value is in a particular range
– A file exists, is writable, is open, etc.
– Some data is sorted
– A network connection to another machine was successfully opened
– …
• The correctness of our program depends on the
validity of our assumptions
• Faulty assumptions result in buggy, unreliable code
Assertions
int binarySearch(int[] data, int searchValue) {
// What assumptions are we making about the parameter values?
…
}
 data != null
 data is sorted
 What happens if these assumptions are wrong?
Assertions
• Assertions give us a way to make our assumptions explicit in the code
• assert temperature > 32 && temperature < 212;
• The parameter to assert is a boolean condition that should be true
• assert condition;
• If the condition is false, Java throws an AssertionError, which crashes
the program
• Stack trace tells you where the failed assertion is in the code
Assertions
int binarySearch(int[] data, int searchValue) {
assert data != null;
assert isSorted(data);
…
}
String[] someMethod(int y, int z) {
assert z != 0;
int x = y / z;
assert x > 0 && x < 1024;
return new String[x];
}
Assertions
• Assertions are little test cases sprinkled throughout your code that
alert you when one of your assumptions is wrong
• This is a powerful tool for avoiding and finding bugs
• Assertions are usually disabled in released software
• In Java, assertions are DISABLED by default
• To turn enable them, run the program with the
–enableassertions (or -ea) option
• java –enableassertions MyApp
• java –ea MyApp
• In Eclipse, the –enableassertions option can be specified in the
VM arguments section of the Run Configuration dialog
Assertions
• Alternate form of assert
• assert condition : expression;
• If condition is false, expression is passed to the constructor of the
thrown AssertionError
int binarySearch(int[] data, int searchValue) {
assert data != null : ”binary search data is null”;
assert isSorted(data) : ”binary search data is not sorted”;
…
}
String[] someMethod(int y, int z) {
assert z != 0 : ”invalid z value”;
int x = y / z;
assert x > 0 && x < 1024 : x;
return new String[x];
}
Assertions
• If one of my assumptions is wrong, shouldn't I
throw an exception?
• No. You should fix the bug, not throw an
exception.
Parameter Checking
• Another important defensive programming technique is "parameter
checking"
• A method or function should always check its input parameters to
ensure that they are valid
• If they are invalid, it should indicate that an error has occurred rather
than proceeding
• This prevents errors from propagating through the code before they
are detected
• By detecting the error close to the place in the code where it
originally occurred, debugging is greatly simplified
Parameter Checking
• Two ways to check parameter values
– assertions
– if statement that throws exception if parameter is invalid
int binarySearch(int[] data, int searchValue) {
assert data != null;
assert isSorted(data);
…
}
int binarySearch(int[] data, int searchValue) {
if (data == null || !isSorted(data)) {
throw new InvalidArgumentException();
}
…
}
Parameter Checking
• Should I use assertions or if/throw to check
parameters?
• If you have control over the calling code, use
assertions
– If parameter is invalid, you can fix the calling code
• If you don't have control over the calling code,
throw exceptions
– e.g., your product might be a class library that is called by code you
don’t control

More Related Content

Similar to DefensiveProgramming (1).pptx

Secure Coding - Web Application Security Vulnerabilities and Best Practices
Secure Coding - Web Application Security Vulnerabilities and Best PracticesSecure Coding - Web Application Security Vulnerabilities and Best Practices
Secure Coding - Web Application Security Vulnerabilities and Best Practices
Websecurify
 
Testing untestable code - STPCon11
Testing untestable code - STPCon11Testing untestable code - STPCon11
Testing untestable code - STPCon11
Stephan Hochdörfer
 
Testing untestable code - phpday
Testing untestable code - phpdayTesting untestable code - phpday
Testing untestable code - phpday
Stephan Hochdörfer
 
Testing untestable code - phpconpl11
Testing untestable code - phpconpl11Testing untestable code - phpconpl11
Testing untestable code - phpconpl11
Stephan Hochdörfer
 
&lt;p>Software Testing&lt;/p>
&lt;p>Software Testing&lt;/p>&lt;p>Software Testing&lt;/p>
&lt;p>Software Testing&lt;/p>
Atul Mishra
 
An overview to Software Testing
An overview to Software TestingAn overview to Software Testing
An overview to Software Testing
Atul Mishra
 

Similar to DefensiveProgramming (1).pptx (20)

Jason Kent - AppSec Without Additional Tools
Jason Kent - AppSec Without Additional ToolsJason Kent - AppSec Without Additional Tools
Jason Kent - AppSec Without Additional Tools
 
Secure Coding - Web Application Security Vulnerabilities and Best Practices
Secure Coding - Web Application Security Vulnerabilities and Best PracticesSecure Coding - Web Application Security Vulnerabilities and Best Practices
Secure Coding - Web Application Security Vulnerabilities and Best Practices
 
Security at Greenhouse
Security at GreenhouseSecurity at Greenhouse
Security at Greenhouse
 
Coding for production
Coding for productionCoding for production
Coding for production
 
Add More Security To Your Testing and Automating - Saucecon 2021
Add More Security To Your Testing and Automating - Saucecon 2021Add More Security To Your Testing and Automating - Saucecon 2021
Add More Security To Your Testing and Automating - Saucecon 2021
 
testing
testingtesting
testing
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - Kenya
 
Testing untestable code - STPCon11
Testing untestable code - STPCon11Testing untestable code - STPCon11
Testing untestable code - STPCon11
 
How to Test PowerShell Code Using Pester
How to Test PowerShell Code Using PesterHow to Test PowerShell Code Using Pester
How to Test PowerShell Code Using Pester
 
black-box testing is a type of software testing in which the tester is not co...
black-box testing is a type of software testing in which the tester is not co...black-box testing is a type of software testing in which the tester is not co...
black-box testing is a type of software testing in which the tester is not co...
 
Testing untestable code - phpday
Testing untestable code - phpdayTesting untestable code - phpday
Testing untestable code - phpday
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Zen and the art of Security Testing
Zen and the art of Security TestingZen and the art of Security Testing
Zen and the art of Security Testing
 
Testing untestable code - phpconpl11
Testing untestable code - phpconpl11Testing untestable code - phpconpl11
Testing untestable code - phpconpl11
 
Bypassing Secure Boot using Fault Injection
Bypassing Secure Boot using Fault InjectionBypassing Secure Boot using Fault Injection
Bypassing Secure Boot using Fault Injection
 
Application Security 101 (OWASP DC)
Application Security 101 (OWASP DC)Application Security 101 (OWASP DC)
Application Security 101 (OWASP DC)
 
Must.kill.mutants. TopConf Tallinn 2016
Must.kill.mutants. TopConf Tallinn 2016Must.kill.mutants. TopConf Tallinn 2016
Must.kill.mutants. TopConf Tallinn 2016
 
Exception handling
Exception handlingException handling
Exception handling
 
&lt;p>Software Testing&lt;/p>
&lt;p>Software Testing&lt;/p>&lt;p>Software Testing&lt;/p>
&lt;p>Software Testing&lt;/p>
 
An overview to Software Testing
An overview to Software TestingAn overview to Software Testing
An overview to Software Testing
 

More from azida3 (14)

Prototyping.eveningclass.ppt
Prototyping.eveningclass.pptPrototyping.eveningclass.ppt
Prototyping.eveningclass.ppt
 
3830100.ppt
3830100.ppt3830100.ppt
3830100.ppt
 
Access Control
Access ControlAccess Control
Access Control
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
codingtechniques1.ppt
codingtechniques1.pptcodingtechniques1.ppt
codingtechniques1.ppt
 
GCSECS-DefensiveDesign.pptx
GCSECS-DefensiveDesign.pptxGCSECS-DefensiveDesign.pptx
GCSECS-DefensiveDesign.pptx
 
Requirments Elicitation.pptx
Requirments Elicitation.pptxRequirments Elicitation.pptx
Requirments Elicitation.pptx
 
Requirements analysis.pptx
Requirements analysis.pptxRequirements analysis.pptx
Requirements analysis.pptx
 
Introduction to SAD.pptx
Introduction to SAD.pptxIntroduction to SAD.pptx
Introduction to SAD.pptx
 
Chap 4 - Requirements Engineering 1.ppt
Chap 4 - Requirements Engineering 1.pptChap 4 - Requirements Engineering 1.ppt
Chap 4 - Requirements Engineering 1.ppt
 
BPM - Activity diagram.pptx
BPM - Activity diagram.pptxBPM - Activity diagram.pptx
BPM - Activity diagram.pptx
 
Use Case Modelling.pptx
Use Case Modelling.pptxUse Case Modelling.pptx
Use Case Modelling.pptx
 
Presentation Use Case Diagram and Use Case Specification.pptx
Presentation Use Case Diagram and Use Case Specification.pptxPresentation Use Case Diagram and Use Case Specification.pptx
Presentation Use Case Diagram and Use Case Specification.pptx
 
Introduction to SAD.pptx
Introduction to SAD.pptxIntroduction to SAD.pptx
Introduction to SAD.pptx
 

Recently uploaded

Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
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
PECB
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 

Recently uploaded (20)

Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
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
 
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"
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
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
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 

DefensiveProgramming (1).pptx

  • 2. Defensive Programming • Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter Checking
  • 3. Assertions • As we program, we make many assumptions about the state of the program at each point in the code – A variable's value is in a particular range – A file exists, is writable, is open, etc. – Some data is sorted – A network connection to another machine was successfully opened – … • The correctness of our program depends on the validity of our assumptions • Faulty assumptions result in buggy, unreliable code
  • 4. Assertions int binarySearch(int[] data, int searchValue) { // What assumptions are we making about the parameter values? … }  data != null  data is sorted  What happens if these assumptions are wrong?
  • 5. Assertions • Assertions give us a way to make our assumptions explicit in the code • assert temperature > 32 && temperature < 212; • The parameter to assert is a boolean condition that should be true • assert condition; • If the condition is false, Java throws an AssertionError, which crashes the program • Stack trace tells you where the failed assertion is in the code
  • 6. Assertions int binarySearch(int[] data, int searchValue) { assert data != null; assert isSorted(data); … } String[] someMethod(int y, int z) { assert z != 0; int x = y / z; assert x > 0 && x < 1024; return new String[x]; }
  • 7. Assertions • Assertions are little test cases sprinkled throughout your code that alert you when one of your assumptions is wrong • This is a powerful tool for avoiding and finding bugs • Assertions are usually disabled in released software • In Java, assertions are DISABLED by default • To turn enable them, run the program with the –enableassertions (or -ea) option • java –enableassertions MyApp • java –ea MyApp • In Eclipse, the –enableassertions option can be specified in the VM arguments section of the Run Configuration dialog
  • 8. Assertions • Alternate form of assert • assert condition : expression; • If condition is false, expression is passed to the constructor of the thrown AssertionError int binarySearch(int[] data, int searchValue) { assert data != null : ”binary search data is null”; assert isSorted(data) : ”binary search data is not sorted”; … } String[] someMethod(int y, int z) { assert z != 0 : ”invalid z value”; int x = y / z; assert x > 0 && x < 1024 : x; return new String[x]; }
  • 9. Assertions • If one of my assumptions is wrong, shouldn't I throw an exception? • No. You should fix the bug, not throw an exception.
  • 10. Parameter Checking • Another important defensive programming technique is "parameter checking" • A method or function should always check its input parameters to ensure that they are valid • If they are invalid, it should indicate that an error has occurred rather than proceeding • This prevents errors from propagating through the code before they are detected • By detecting the error close to the place in the code where it originally occurred, debugging is greatly simplified
  • 11. Parameter Checking • Two ways to check parameter values – assertions – if statement that throws exception if parameter is invalid int binarySearch(int[] data, int searchValue) { assert data != null; assert isSorted(data); … } int binarySearch(int[] data, int searchValue) { if (data == null || !isSorted(data)) { throw new InvalidArgumentException(); } … }
  • 12. Parameter Checking • Should I use assertions or if/throw to check parameters? • If you have control over the calling code, use assertions – If parameter is invalid, you can fix the calling code • If you don't have control over the calling code, throw exceptions – e.g., your product might be a class library that is called by code you don’t control