Programming with Assertions © Allan C. Milne v15.4.13.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

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.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.
1 Week 11 l Basic Exception Handling »the mechanics of exceptions l Defining and Using Exceptions »some "simple" cases l Reality Check »guidelines for.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 13 Exception.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
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 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions and Assertions Animated Version.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Fall 2007CS 225 Program Correctness and Efficiency Chapter 2.
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.
Exceptions COMPSCI 105 S Principles of Computer Science.
Ranga Rodrigo. Class is central to object oriented programming.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
1 Chapter 18 Exception Handling. 2 Motivations F Program runs into a runtime error –program terminates abnormally F How can you handle the runtime error.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Exception Handling.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
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.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
Introduction to Exception Handling and Defensive Programming.
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.
ECE122 Feb. 22, Any question on Vehicle sample code?
Pre- and postconditions, Using assertions and exceptions 1 Pre- and postconditions Using assertions and exceptions.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Chapter 5 Selection Statements Mr. Dave Clausen La Cañada High School.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions and Assertions Chapter 15 – CSCI 1302.
L13: Design by Contract Definition Reliability Correctness Pre- and post-condition Asserts and Exceptions Weak & Strong Conditions Class invariants Conditions.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
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.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 15 Exceptions and Assertions Nothing is impossible.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
Winter 2006CISC121 - Prof. McLeod1 Stuff Midterm exam in JEF234 on March 9th from 7- 9pm.
Chapter 13 Exception Handling
Logger, Assert and Invariants
Topics: jGRASP editor ideosyncrasies assert debugger.
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
CNS 3260 C# .NET Software Development
Conditions and Ifs BIS1523 – Lecture 8.
Programming in Java Assertion.
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.
CS-1020 and Exception Handling
Computer Science 340 Software Design & Testing
Chapter 5 Selection Statements
Defensive Programming
Presentation transcript:

Programming with Assertions © Allan C. Milne v

Agenda. What are assertions? Use of assertions. When not to use assertions. the Java assert statement. Examples of using assertions.

What are assertions? Tests that assumptions you make about the state of your program are in fact correct. Note that they are not about validating state that might occur (either as an error or invalid state); this should be checked in the usual programmatic manner. Assertions relate to assumptions about normal operation of your program; normal operation includes handling invalid and error conditions.

Calculate distance travelled … … from various values within the program;  assume that all values have been appropriately validated;  assume the calculation is correctly implemented. We can assert that distance travelled is >= 0.

So what? If the assertion fails then the program will fail with an appropriate assertion error: unhandled exception error message; stack trace will be displayed. this tells the developer that some of the assumptions made are incorrect; the developer must revisit their design and/or implementation.

Execution time. You might think that using assertions liberally within a program will result in slower, less efficient execution times. this is not the case as, in Java, assertions are disabled by default and have zero impact on execution time. Assertions can be enabled by invoking Java with the ‘-ea\ flag: java –ea MyProgram

Typical workflow. Developer includes assertions in their code. Enable assertions during testing. Normal operation executes the program with assertions disabled. On unexpected program results or crash: rerun with assertions enabled; debug and test with assertions enabled until repaired.

Why use assertions? No-cost for normal execution-time operation. Gives more confidence in the correctness of software. Aids in debugging unexpected faults. Self-documenting code Leads to more robust software.

Don’t use assertions for … … validation of values. … detection of error conditions. … checking parameter values in public methods. … any application-level logic.

The Java assert statement. assert boolean-expr if the boolean-expr is false then an AssertionError is thrown. assert boolean-expr : expr as above; expr is evaluated to a string and included in the error message.

use assert for. Pre- and post-conditions. Control flow invariants. class state invariants.

Pre- and post-conditions. What must be true before and/or after some processing unit: a method, but note not for checking parameters of a public method; a computation; synchronisation lock status; etc.

Examples. // compute distance travelled … distance = … assert distance>=0.0 : distance; // private helper method; we assume that // parameters are validated in the public code. private void doSomething (int units, String message) { assert (units>10) && (message!=null); … … … }

control-flow invariants. Assert the assumed condition for the last else clause in a multi-way if. Assert places in the code that you assume cannot be reached; for example the default clause in a ‘closed’ case. Use assert false; for this.

Examples. PlayingCard card; … … … switch (card.suit()) { case Suit.Hearts: … … … break; case Suit.Clubs: … … … break; case Suit.Diamonds: … … … break; case Suit.Spades: … … … break; default: assert false : card.suit(); // or alternatively use the statement: //throw new AssertionError (card.suit()); } int minutes; … … … final int quarter = minutes % 60 / 15; if (quarter == 0) { … … … } else if (quarter == 1) { … … … } else if (quarter == 2) { … … … } else { assert quarter==3; … … … }

Class state invariants. What must be true about the state of every instance of a class. Often this is the assumptions made about the relationships between the values of the fields making up the object’s state. Define in a private helper function; call the function from assert statements; include these statements at the end of all public methods.

State invariant coding pattern // constructor method. public YoHo (…) { … … … assert isConsistent(); } // … and for all public methods … public void doThis (…) { … … … assert isConsistent(); } … … … } // end YoHo class. class YoHo { // private fields defining an object state … … … … // Helper function defining consistency. private boolean isConsistent () { // perform appropriate checks on object state. … … … }

Reference links. Oracle documentation: Programming guide on using assert. Programming guide on using assert Wikipedia: Assertions in software development.