Defensive Programming

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.
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.
FIT FIT1002 Computer Programming Unit 19 Testing and Debugging.
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.
Fall 2007CS 225 Program Correctness and Efficiency Chapter 2.
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
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
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 –
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.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
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.
Coding Defensively Coding Defensively
CSS 161: Fundamentals of Computing
Chapter 14: Exception Handling
Advanced Programming Behnam Hatami Fall 2017.
Programming in Java Assertion.
Part B – Structured Exception Handling
Testing, debugging, and using support libraries
Homework Any Questions?.
Exceptions 19-Feb-19.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
Handling Exceptionally Sticky Problems
CS-1020 and Exception Handling
Chapter 3 Debugging Section 3.4
Computer Science 340 Software Design & Testing
Review of Previous Lesson
Exceptions 5-Jul-19.
Exception Handling and Event Handling
Presentation transcript:

Defensive Programming CS 240 – Advanced Programming Concepts

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 data != null data is sorted 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 enable them, run the program with the –enableassertions (or -ea) option java –enableassertions MyApp java –ea MyApp In Intellij, the –enableassertions option can be specified in the VM options section of the Run/Debug Configurations 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); … } 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