Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.

Slides:



Advertisements
Similar presentations
11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
Advertisements

1. Define the concept of assertions. 1 Explain the use of assertions. 2 Create Java program using assertions. 3 Run Java program using assertions. 4 2.
Error-handling using exceptions
Detecting Bugs Using Assertions Ben Scribner. Defining the Problem  Bugs exist  Unexpected errors happen Hardware failures Loss of data Data may exist.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
Chapter 1. The Phases of Software Development. Data Structure 2 Chapter outline  Objectives  Use Javadoc to write a method’s complete specification.
FIT FIT1002 Computer Programming Unit 19 Testing and Debugging.
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.
The Java Assert Statement. 2 Assert A Java statement in JDK 1.4 & newer Intent: enables code to test assumptions. E.g., a method that calculates a particle’s.
1 TCSS 360, Spring 2005 Lecture Notes Programming by Contract: Pre/Postconditions, Invariants and Assertions Relevant Reading: Object-Oriented Design and.
Program Input and the Software Design Process ROBERT REAVES.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Computer Science 340 Software Design & Testing Design By Contract.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
Chapter 12: Exception Handling
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.
Computer Security and Penetration Testing
Testing CSE 140 University of Washington 1. Testing Programming to analyze data is powerful It’s useless if the results are not correct Correctness is.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
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?
1 Assertions. 2 assertions communicate assumptions about the state of the program, and stop processing if they turn out to be false very often comments.
Exceptions Handling Exceptionally Sticky Problems.
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
VB.Net - Exceptions Copyright © Martin Schray
Object Oriented Software Development 8. Exceptions, testing and debugging.
Introduction to Exception Handling and Defensive Programming.
Exceptions and assertions CSE 331 University of Washington.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Programming with Assertions © Allan C. Milne v
Pre- and postconditions, Using assertions and exceptions 1 Pre- and postconditions Using assertions and exceptions.
Design - programming Cmpe 450 Fall Dynamic Analysis Software quality Design carefully from the start Simple and clean Fewer errors Finding errors.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
The Java Assertion. 2 Assertion A Java statement in JDK 1.4 & newer Intent: enables code to test assumptions. E.g., a method that calculates the a particle’s.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Chapter 13 Exception Handling
Chapter 6 CS 3370 – C++ Functions.
Logger, Assert and Invariants
Handling Exceptionally Sticky Problems
Defensive Programming
Topics: jGRASP editor ideosyncrasies assert debugger.
Testing and Debugging.
Chapter 14: Exception Handling
Advanced Programming Behnam Hatami Fall 2017.
Programming in Java Assertion.
Testing, debugging, and using support libraries
Homework Any Questions?.
Handling Exceptionally Sticky Problems
CS-1020 and Exception Handling
Chapter 3 Debugging Section 3.4
Computer Science 340 Software Design & Testing
Defensive Programming
Presentation transcript:

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 –enableassertion s (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