Defensive Programming

Slides:



Advertisements
Similar presentations
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Advertisements

 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 7: Errors 1 Based on slides created by Bjarne Stroustrup.
Software Construction 1 ( ) First Semester Dr. Samer Odeh Hanna (PhD) Office: IT 327.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Computer Science 340 Software Design & Testing Design By Contract.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Code Complete Steve McConnell.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
1 Defensive Programming and Debugging (Chapters 8 and 23 of Code Complete) Tori Bowman CSSE 375, Rose-Hulman September 21, 2007.
Chapter 12: Exception Handling
Software Construction and Evolution - CSSE 375 Defensive Programming & Error Handling Shawn & Steve Above – As you see behind me on the shelf, there are.
1 Debugging and Testing Overview Defensive Programming The goal is to prevent failures Debugging The goal is to find cause of failures and fix it Testing.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
Introduction to Exception Handling and Defensive Programming.
Defensive Programming, Assertions and Exceptions Designing Fault-Resistant Code SoftUni Team Technical Trainers Software University
Defensive Programming, Assertions and Exceptions Designing Error Steady Code SoftUni Team Technical Trainers Software University
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
2.4 Exceptions n Detects try { //code that may raise an exception and/or set some condition if (condition) throw exceptionName; //Freq. A string } n Handles.
Eighth Lecture Exception Handling in Java
SE-1021 Software Engineering II
C++ Exceptions.
Exceptions.
CMSC202 Computer Science II for Majors Lecture 16 – Exceptions
Chapter 6 CS 3370 – C++ Functions.
Exceptions In this lecture:
Logger, Assert and Invariants
Andy Wang Object Oriented Programming in C++ COP 3330
CSE 374 Programming Concepts & Tools
Testing and Debugging.
Why exception handling in C++?
The Pseudocode Programming Process
Scripts & Functions Scripts and functions are contained in .m-files
Fall 2017 CISC124 9/21/2018 CISC124 First onQ quiz this week – write in lab. More details in last Wednesday’s lecture. Repeated: The quiz availability.
Chapter 14: Exception Handling
Some Basics for Problem Analysis and Solutions
Software Construction
Topics Introduction to File Input and Output
Exceptions & Error Handling
CSC 143 Error Handling Kinds of errors: invalid input vs programming bugs How to handle: Bugs: use assert to trap during testing Bad data: should never.
COP4020 Programming Languages
Throwing and catching exceptions
Part B – Structured Exception Handling
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Exceptions 19-Feb-19.
Exceptions 7-Apr-19.
CMSC 202 Exceptions 2nd Lecture.
Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
Java Statements B.Ramamurthy CS114A, CS504 4/23/2019 BR.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
CSC 143 Java Errors and Exceptions.
SWE 619 Last modified Fall 2007 Saket Kaushik, Paul Ammann
Exceptions 10-May-19.
Computer Science 340 Software Design & Testing
Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
Topics Introduction to File Input and Output
Exceptions 5-Jul-19.
CMSC 202 Exceptions 2nd Lecture.
Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
Software Construction
Defensive Programming
Presentation transcript:

Defensive Programming SCMP 391.00 Special Topic: Software Development Spring 2017 James Skon

Defensive Programming What is it?

Protecting Your Program from Invalid Inputs “Garbage in, garbage out.” NEVER output garbage! What to do? Check the values of all data from external sources Check the values of all routine input parameters Decide how to handle bad inputs

Assertions An assertion is code that's used during development usually a routine or macro allows a program to check itself as it runs When true - everything is operating as expected An assertion usually takes two arguments: a boolean expression that describes the assumption that's supposed to be true and a message to display if it isn't

C++ Assert Example ASSERT - aborts the program if the parameter passed to the macro does not evaluate to true int g_anArray[10]; // a global array of 10 characters #include <cassert> // for assert() int GetArrayValue(int nIndex){ // we're asserting that nIndex is between 0 and 9 assert(nIndex >= 0 && nIndex <= 9); // check index return g_anArray[nIndex]; }

Where to use Assert That an input parameter's value falls within its expected range (or an output parameter's value does) That a file or stream is open (or closed) when a routine begins executing (or when it ends executing) That a file or stream is at the beginning (or end) when a routine begins executing (or when it ends executing) That a file or stream is open for read-only, write-only, or both read and write That the value of an input-only variable is not changed by a routine

Where to use Assert That a pointer is non-null That an array or other container passed into a routine can contain at least X number of data elements That a table has been initialized to contain real values That a container is empty (or full) when a routine begins executing (or when it finishes) That the results from a highly optimized, complicated routine match the results from a slower but clearly written routine

Assertions Use error-handling code for conditions you expect to occur; use assertions for conditions that should never occur Use conditional compilation to allow assertions to be “turned off” Avoid putting executable code into assertions # defin my_Debug … #ifdef my_Debug Assert( PerformAction() )

Assert For highly robust code, assert and then handle the error anyway

Assertions Use to both document and check preconditions and postconditions. Private Function Velocity ( int &latitude; int &longitude; int &elevation) As Single /* Preconditions */ Assert ( -90 <= latitude && latitude <= 90 ) Assert ( 0 <= longitude && longitude < 360 ) Assert ( -500 <= elevation && elevation <= 75000 ) ... /*Sanitize input data. */ If ( latitude < -90 ) { latitude = -90; } elseif ( latitude > 90 ) { latitude = 90 End If If ( longitude < 0 ) Then longitude = 0 ElseIf ( longitude > 360 ) Then Checking preconditions Checking postconditions

Error-Handling Techniques How do you handle errors that you do expect to occur? Return a neutral value (background color) Substitute the next piece of valid data (database) Return the same answer as the previous time (thermostat) Substitute the closest legal value (velocity) Log a warning message to a file

Error-Handling Techniques How do you handle errors that you do expect to occur? Call an error-processing routine/object (centralized) Display an error message wherever the error is encountered Handle the error in whatever way works best locally Shut down

Robustness vs. Correctness Correctness: never returning an inaccurate result; returning no result is better than returning an inaccurate result. Robustness: always trying to do something that will allow the software to keep operating, even if that leads to results that are inaccurate sometimes.

Barricade Barricade Your Program to Contain the Damage Caused by Errors

Relationship Between Barricades and Assertions Barricades – Routines outside the barricade should use error handling because it isn't safe to make any assumptions about the data. Assertions - 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.

Debugging Aids Code may have to “modes”, development and production. Development – checks for internal errors, provides intermediate results. Production – Streamlines and fast, does’ty show internal state.

Debugging Aids A dead program normally does a lot less damage than a crippled one. —Andy Hunt and Dave Thoma

Use Offensive Programming Make sure asserts abort the program. Completely fill any memory allocated so that you can detect memory allocation errors. Completely fill any files or streams allocated to flush out any file-format errors. Be sure the code in each case statement's default or else clause fails hard (aborts the program) or is otherwise impossible to overlook. Fill an object with junk data just before it's deleted. Set up the program to e-mail error log files to yourself so that you can see the kinds of errors that are occurring in the released software, if that's appropriate for the kind of software you're developing.

Plan to Remove Debugging Aids Option one: Wrap all debug code in a conditional: Define to include Debug code #define DEBUG ... #if defined( DEBUG ) // debugging code #endif Wrap all debug code in conditional

Debug Macro contains conditional Plan to Remove Debugging Aids Option one: Create special debug Macro. #define DEBUG #if defined( DEBUG ) #define DebugCode( parameters ) { code_fragment } #else #define DebugCode(parameterst ) #endif ... DebugCode( statement 1; statement 2; statement n; ); Debug Macro contains conditional This code is included or excluded, depending on whether DEBUG has been defined.

How Much Defensive Programming should be left in Production Code? Leave in code that checks for important errors: Is the result significant or not (invalid answer vs. formatting error) 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 Make sure that the error messages you leave in are friendly

Review – General checklist Does the routine protect itself from bad input data? Have you used assertions to document assumptions, including preconditions and postconditions? Have assertions been used only to document conditions that should never occur? Does the architecture or high-level design specify a specific set of error-handling techniques? Does the architecture or high-level design specify whether error handling should favor robustness or correctness? Have barricades been created to contain the damaging effect of errors and reduce the amount of code that has to be concerned about error processing? Have debugging aids been used in the code? Have debugging aids been installed in such a way that they can be activated or deactivated without a great deal of fuss? Is the amount of defensive programming code appropriate—neither too much nor too little? Have you used offensive-programming techniques to make errors difficult to overlook during development?

Review - Exceptions Has your project defined a standardized approach to exception handling? Have you considered alternatives to using an exception? Is the error handled locally rather than throwing a nonlocal exception, if possible? Does the code avoid throwing exceptions in constructors and destructors? Are all exceptions at the appropriate levels of abstraction for the routines that throw them? Does each exception include all relevant exception background information? Is the code free of empty catch blocks? (Or if an empty catch block truly is appropriate, is it documented?)

Review - Security Issues Does the code that checks for bad input data check for attempted buffer overflows, SQL injection, HTML injection, integer overflows, and other malicious inputs? Are all error-return codes checked? Are all exceptions caught? Do error messages avoid providing information that would help an attacker break into the system?