Defensive Programming

Similar documents
Encapsulation. Contents. Steven Zeil. July 17, Encapsulation Encapsulation in C Classes 4. 3 Hiding Attributes 8

Operator Overloading

The Structure of a C++ Program

Unit Testing. Contents. Steven Zeil. July 22, Types of Testing 2. 2 Unit Testing Scaffolding Drivers Stubs...

Unit Testing. Steven Zeil. July 22, Types of Testing 2. 2 Unit Testing Scaffolding Drivers Stubs...

Common Modifications of Class Members

Common Modifications of Class Members

Common Modifications of Class Members

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2

Operator Overloading

The Structure of a C++ Program

Pointers and References

Patterns: Working with Arrays

Linked Lists. Contents. Steven J. Zeil. July 31, Linked Lists: the Basics 4

Linked Lists. Contents. Steven J. Zeil. July 31, Linked Lists: the Basics 3

OBJECT ORIENTED PROGRAMMING USING C++

A C++ Class Designer s Checklist

CSI33 Data Structures

EECE.3220: Data Structures Spring 2017

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Lecture 7. Log into Linux New documents posted to course webpage

QUIZ. What are 3 differences between C and C++ const variables?

Intermediate Programming, Spring 2017*

III. Classes (Chap. 3)

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Java - First Impressions for a C++ Programmer

Chapter 2. Procedural Programming

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

CSCE 110 PROGRAMMING FUNDAMENTALS

Introducing C++ to Java Programmers

pointers + memory double x; string a; int x; main overhead int y; main overhead

Practice Problems CS2620 Advanced Programming, Spring 2003

Week 5: Files and Streams

CSE 303, Winter 2007, Final Examination 15 March Please do not turn the page until everyone is ready.

CS11 Intro C++ Spring 2018 Lecture 3

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

CSE 303, Winter 2007, Final Examination 15 March Please do not turn the page until everyone is ready.

Security Coding Module - Buffer Overflow Data Gone Wild CS1

Lab: Supplying Inputs to Programs

CSE143 Exam with answers MIDTERM #1, 1/26/2001 Problem numbering may differ from the test as given.

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

CS102 C++ Exception Handling & Namespaces

Bruce Merry. IOI Training Dec 2013

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup.

Chapter 5 Errors. Bjarne Stroustrup

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

G52CPP C++ Programming Lecture 17

CS 240 Data Structure Spring 2018 Exam I 03/01/2018

C++_ MARKS 40 MIN

CS24 Week 3 Lecture 1

C C C C++ 2 ( ) C C++ 4 C C

Functions & Libraries

10/23/02 21:20:33 IO_Examples

3. Logical Values. Our Goal. Boolean Values in Mathematics. The Type bool in C++

3. Logical Values. Our Goal. Boolean Values in Mathematics. The Type bool in C++

Review: C++ Basic Concepts. Dr. Yingwu Zhu

COMP322 - Introduction to C++

Sets and MultiSets. Contents. Steven J. Zeil. July 19, Overview of Sets and Maps 4

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Intermediate Programming, Spring 2017*

CS2255 HOMEWORK #1 Fall 2012

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

Due Date: See Blackboard

Using the Xcode Debugger

1 Unit 8 'for' Loops

C++ STREAMS; INHERITANCE AS

Implementing an ADT with a Class

CSE 303, Autumn 2006, Final Examination 12 December 2006

Pointers, Arrays and C-Strings

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Unified Modeling Language a case study

CSE 303: Concepts and Tools for Software Development

CSI33 Data Structures

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

PIC 10A. Lecture 17: Classes III, overloading

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

Summary of basic C++-commands

CSCI 1061U Programming Workshop 2. C++ Basics

CPSC 427: Object-Oriented Programming

QUIZ. Source:

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

CS93SI Handout 04 Spring 2006 Apr Review Answers

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Software Design and Analysis for Engineers

Recursion. Contents. Steven Zeil. November 25, Recursion 2. 2 Example: Compressing a Picture 4. 3 Example: Calculator 5

typedef Labeling<unsigned char,short> LabelingBS; typedef Labeling<unsigned char,short>::regioninfo RegionInfoBS;

Computer Programming. Basic Control Flow - Decisions. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

File I/O CS 16: Solving Problems with Computers I Lecture #9

Unit 7. 'while' Loops

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

OBJECT ORIENTED PROGRAMMING USING C++

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

CIS 190: C/C++ Programming. Classes in C++

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Transcription:

Steven Zeil July 22, 2013 Contents 1 Common Assumptions 2 2 Documenting Assumptions 2 3 Guarding Assumptions 5 3.1 Guarding Assumptions with Assertions............................... 8 1

Defensive Programming Defensive programming is an approach to coding based on minimizing assumptions made by the programmer. Assumes that things will go wrong Tries to predict and allow for likely problems 1 Common Assumptions The Glass is Half-Full Programmers are optimists by nature. We always believe that our programs are actually going to run "as soon as I fix this one little problem" despite the fact that, time and time again, we are proven wrong. Programmers Like to Assume... Program input will be good Function parameters will be good Algorithms will behave as expected (no bugs) Odds are, if we weren t such blind optimists, we would never actually dare to write a single line of code. What to do About Assumptions? Document them Guard them 2 Documenting Assumptions Preconditions It s common for functions to only work under certain circumstances. A precondition is a condition that must be true before the function is called, if we expect the function to do anything reasonable. Preconditions are an obligation on the caller, not on the function being called CS250 2

Documenting Preconditions Preconditions should be documented in the function declaration. Have to be visible to callers Pre-Condition Example Look at addintimeorder in #ifndef BIDCOLLECTION_H #define BIDCOLLECTION_H #include "bids.h" class BidCollection int MaxSize; int size; Bid* elements; // array of bids public: /** * Create a collection capable of holding the indicated number of bids */ BidCollection (int MaxBids = 1000); ~BidCollection (); // Access to attributes int getmaxsize() const return MaxSize; int getsize() const return size; // Access to individual elements CS250 3

const Bid& get(int index) const return elements[index]; // Collection operations void addintimeorder (const Bid& value); // Adds this bid into a position such that // all bids are ordered by the time the bid was placed //Pre: getsize() < getmaxsize() void remove (int index); // Remove the bid at the indicated position //Pre: 0 <= index < getsize() /** * Read all bids from the indicated file */ void readbids (std::string filename); ; #endif Internal Assumptions Internal assumptions can be documented with comments. E.g., in resolveauction, // If highestbidsofar is non-zero, we have a winner if (reservepricemet && highestbidsofar > 0.0) int biddernum = bidders.findbidder(winningbiddersofar); // winningbiddersofar should be in the list of registered bidders CS250 4

cout << item.getname() << " won by " << winningbiddersofar << " for " << highestbidsofar << endl; Bidder& bidder = bidders.get(biddernum); bidder.setbalance (bidder.getbalance() - highestbidsofar); biddernum should be valid, because all bids should be placed by bidders registered with the auction. So we document this... 3 Guarding Assumptions Guarding Assumptions Suppose that you have written a function that has a precondition you documented the precondition but your function is called with illegal parameters It s not your fault, but what do you do? Possible Reactions Abort the program with an error message Ignore it and let the program continue Quietly correct the input and let the program continue. Issue an error message, correct the input, and let the program continue. Example E.g., for CS250 5

int BidderCollection : : add ( const Bidder& value ) / / Adds t h i s bidder / / Pre : getsize ( ) < getmaxsize ( ) addtoend ( elements, size, value ) ; return s i z e 1 ; What should we do if add is called on a full collection? Abort the program with an error message int BidderCollection::add (const Bidder& value) // Adds this bidder //Pre: getsize() < getmaxsize() if (size < MaxSize) else addtoend (elements, size, value); return size - 1; cerr << "BidderCollection::add - collection is full" << endl; exit(1); OK (but we ll see an easier way to do this). Some people are appalled at the idea of a program aborting is "real use", but the alternatives are often worse. Ignore it and let the program continue Worst thing we can do We know that things are going badly, but we re going to risk incorrect output, corrupted output files and databases, etc. CS250 6

Quietly correct the input and let the program continue int BidderCollection::add (const Bidder& value) // Adds this bidder //Pre: getsize() < getmaxsize() if (size < MaxSize) addtoend (elements, size, value); return size - 1; else elements[size-1] = value; Nearly as dangerous as just letting the program run. Usually cannot reasonably guess whether a given correction is safe or not Issue an error message, correct the input, and let the program continue int BidderCollection::add (const Bidder& value) // Adds this bidder //Pre: getsize() < getmaxsize() if (size < MaxSize) addtoend (elements, size, value); return size - 1; else cerr << "BidderCollection::add - collection is full" << endl; elements[size-1] = value; CS250 7

Occasionally the best choice. Depends on if anyone is watching for such error messages 3.1 Guarding Assumptions with Assertions Guarding Assumptions with Assertions assert(c); (from the header file <cassert>) tests to see if a boolean condition c is true. If not, it issues an error message and aborts the program. Assertions can be deactivated by compiling with the macro symbol NDEBUG defined. assert() Example if (reservepricemet && highestbidsofar > 0.0) int biddernum = bidders.findbidder(winningbiddersofar); // winningbiddersofar should be in the list of registered bidders assert (biddernum >= 0 && biddernum < bidders.getsize()); cout << item.getname() << " won by " << winningbiddersofar << " for " << highestbidsofar << endl; Bidder& bidder = bidders.get(biddernum); bidder.setbalance (bidder.getbalance() - highestbidsofar); Guarding Preconditions Perhaps the most common use of assertions is in guarding pre-conditions. #include <iostream> #include "arrayutils.h" #include <fstream> #include <cassert> #include "biddercollection.h" CS250 8

using namespace std; /** * Create a collection capable of holding the indicated number of items */ BidderCollection::BidderCollection (int MaxBidders) : MaxSize(MaxBidders), size(0) elements = new Bidder [MaxSize]; BidderCollection::~BidderCollection () delete [] elements; // Collection operations int BidderCollection::add (const Bidder& value) // Adds this bidder //Pre: getsize() < getmaxsize() assert (size < MaxSize); addtoend (elements, size, value); return size - 1; void BidderCollection::remove (int index) // Remove the bidder at the indicated position //Pre: 0 <= index < getsize() assert (0 <= index && index < MaxSize); removeelement (elements, size, index); CS250 9

/** * Read all bidders from the indicated file */ void BidderCollection::readBidders (std::string filename) size = 0; ifstream in (filename.c_str()); int nbidders; in >> nbidders; for (int i = 0; i < nbidders && i < MaxSize; ++i) string nme; double bal; in >> nme >> bal; Bidder bidder (nme, bal);; add (bidder); /** * Find the index of the bidder with the given name. If no such bidder exists, * return nbidders. */ int BidderCollection::findBidder (std::string name) const int found = size; for (int i = 0; i < size && found == size; ++i) if (name == elements[i].getname()) found = i; return found; // Print the collection CS250 10

void BidderCollection::print (std::ostream& out) const out << size << "/" << MaxSize << ""; for (int i = 0; i < size; ++i) out << " "; elements[i].print (out); out << "\n"; out << ""; If a program aborts because of a guarded precondition in a function, it s not the function s fault It indicates a failure in the calling code. CS250 11