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.

Slides:



Advertisements
Similar presentations
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 18 Program Correctness To treat programming.
Advertisements

Design By Contract Using JMSAssert.
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
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.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions.
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.
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
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.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Software Testing and Quality Assurance
1 TCSS 360, Spring 2005 Lecture Notes Programming by Contract: Pre/Postconditions, Invariants and Assertions Relevant Reading: Object-Oriented Design and.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Information Hiding and Encapsulation
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Computer Science 340 Software Design & Testing Design By Contract.
Component-Based Software Engineering Components and Interfaces Paul Krause.
Ranga Rodrigo. Class is central to object oriented programming.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
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.
COSC 2006 Data Structures I Recursion II
The Java Programming Language
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.
Low-Level Detailed Design SAD (Soft Arch Design) Mid-level Detailed Design Low-Level Detailed Design Design Finalization Design Document.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
A Survey on Java Modeling Languages Gergely Kovásznai,Eszterházy Károly College Wolfgang Schreiner,Johannes Kepler University Gábor Kusper,Eszterházy Károly.
P Chapter 2 introduces Object Oriented Programming. p OOP is a relatively new approach to programming which supports the creation of new data types and.
OOSC - JMSAssert. Design By Contract A powerful technique for writing reliable software. Specifying the software purpose with the implementation. Key.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
Programming with Assertions © Allan C. Milne v
Pre- and postconditions, Using assertions and exceptions 1 Pre- and postconditions Using assertions and exceptions.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
David Streader Computer Science Victoria University of Wellington Copyright: David Streader, Victoria University of Wellington Debugging COMP T1.
Computer Science 209 Software Development Handing Errors and Creating Documentation.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Class Design I Class Contracts Readings: 2 nd Ed: Section 9.5, Advanced Topic nd Ed: Section 8.5, Advanced Topic 8.2 Some ideas come from: “Practical.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
L13: Design by Contract Definition Reliability Correctness Pre- and post-condition Asserts and Exceptions Weak & Strong Conditions Class invariants Conditions.
Lecture 5 functions 1 © by Pearson Education, Inc. All Rights Reserved.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
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 PRE- AND POSTCONDITIONS, INVARIANTS AND METHOD CONTRACTS B MODULE 2: SOFTWARE SYSTEMS 13 NOVEMBER 2013.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
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.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
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.
Programming in Java Assertion.
Chapter 11 Exception Handling and Text I/O
CSE 143 Java Exceptions 1/18/2019.
CS-1020 and Exception Handling
Computer Science 340 Software Design & Testing
Corresponds with Chapter 5
Defensive Programming
Presentation transcript:

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 speed, asserts: speed < c (speed of light). Has a boolean expression whose value is “asserted” to be true when the assertion executes. –If it is false, the system throws an error. –By evaluating the boolean expression, the assertion confirms assumptions about program behavior. Increases confidence that the program is error-free.

3 Assertion … Assert: Detecting bugs is quicker when assertions are included in the code. Assertions also document the program, enhancing maintainability.

4 Outline Introduction Using Assertions Compiling Files That Use Assertions Enabling & Disabling Assertions

5 Introduction The assertion statement has 2 forms: assert Expression; // Expression 1 is boolean Meaning: if ( ! Expression ) { throw AssertionError // no message AssertionError }

6 Introduction … assert Expression1 : Expression2 ; where: –Expression1 is boolean –Expression2 has a value Cannot be the returned value of a void method. Meaning: if ( ! Expression1 ) { throw new AssertionError( Expression2 )AssertionError } // Expression2’s String value is the message.

7 The Message Should convey details of the assertion failure Is not a user-level message Need not be understandable in isolation Is intended for use with: –a full stack trace –the source code.

8 Introduction … The stack trace gives the file/line# of the failed assertion. Use the message form only to add information that helps diagnose the failure. E.g., if Expression 1 involves a relationship between variables x & y, use the message form. E.g., assert x < y : “x: “ + x + “, y: “ + y ;

9 Introduction … Assertions can be enabled or disabled when the program is started. Assertions are disabled by default. Disabled assertions are equivalent to empty statements in semantics & performance.

10 Outline Introduction Using Assertions Compiling Files That Use Assertions Enabling & Disabling Assertions

11 Using Assertions Do not use assertions for: argument checking in public methods. Argument checking is part of the method’s published specifications (or contract): Specifications are obeyed whether or not assertions are enabled. Assert’s expression should have no side- effects. Exception: assertions can modify state used only from within other assertions (illustrated later).

12 Internal Invariants Replace if ( i % 3 == 0 ) {... } else if ( i % 3 == 1 ) {... } else { // We know ( i % 3 == 2 )... } With if ( i % 3 == 0 ) {... } else if ( i % 3 == 1 ) {... } else { assert i % 3 == 2 : i;... } // assert fails for i = -5

13 Control-Flow Invariants Use: assert false; // an unreachable point Replace void foo() { for (...) { if (...) return; } // unreachable point } With void foo() { for (...) { if (...) return; } assert false; // unreachable }

14 Control-Flow Invariants Use: assert false; // an unreachable point The foregoing only makes sense if reaching a point is possible but erroneous. If it is impossible, the compiler handles it. If it is possible, you may always throw an exception Not just when assertions are enabled. Replace “assert false; ” with “throw new AssertionError(); ”

15 Preconditions Do not assert method contracts /** * Sets the refresh rate. rate refresh rate, in frames per second. IllegalArgumentException if rate <= 0 or * rate > MAX_REFRESH_RATE. */ public void setRefreshRate(int rate) { // Enforce specified precondition in public method if (rate MAX_REFRESH_RATE) throw new IllegalArgumentException("Illegal rate: " + rate); setRefreshInterval(1000/rate); }

16 Preconditions … Assert a nonpublic method's precondition. An assertion is appropriate in the following “helper” method invoked by the previous method.

17 /** * Sets the refresh interval (to a legal frame rate). interval refresh interval in milliseconds. */ private void setRefreshInterval( int interval ) { // Confirm adherence to precondition in nonpublic method assert interval > 0 && interval <= 1000/MAX_REFRESH_RATE : interval;... // Set the refresh interval } The assertion can fail if MAX_REFRESH_RATE > 1000.

18 Lock-Status Precondition Original private Object[] a; public synchronized int find(Object key) { return find(key, a, 0, a.length); } // Recursive helper method: always has lock on this private int find(Object key, Object[] arr, int start, int len) {... } Assert lock status: // Recursive helper method: always has lock on this. private int find(Object key, Object[] arr, int start, int len) { // lock-status assertion assert Thread.holdsLock(this);Thread.holdsLock... }

19 Postconditions Replace void push( Object o ) { … stack.add( ++top, o ); // top == stack.size(); } With void push( Object o ) { … stack.add( ++top, o ); assert top == stack.size() : “top: ” + top + “, size: ” + stack.size(); }

20 Postconditions … An assert’s expression may need state. void foo(int[] array) { // Manipulate array... // At this point, array contents == itself // prior to manipulation } Replace the above with the following.

21 Postconditions … void foo(final int[] array) { // Inner class that saves state & performs final consistency check class DataCopy { private int[] arrayCopy; DataCopy() { arrayCopy = ( int[] ) array.clone(); } boolean isConsistent() { return Arrays.equals( array, arrayCopy ); }Arrays.equals } DataCopy copy = null; // Always succeeds; has side effect of saving a copy of array assert ( ( copy = new DataCopy() ) != null ); // copy only if ea... // Manipulate array // Ensure array has same ints in same order as before. assert copy.isConsistent(); }

22 Class State Invariants Class state invariant: an invariant that applies to all instances at the beginning & ending of all methods. E.g., in a balanced tree, a class invariant is that the tree is balanced. Style: combine the expressions that check required constraints into an internal method. // Returns true if this tree is properly balanced private boolean isBalanced() {... } Assert class invariant just prior to return from public methods & constructors: assert isBalanced();

23 Outline Introduction Using Assertions Compiling Files That Use Assertions Enabling & Disabling Assertions Compatibility with Existing Programs

24 Compiling Files That Use Assertions To tell javac to accept assertions, use the - source 1.4 command-line option: javac -source 1.4 MyClass.java

25 Outline Introduction Using Assertions Compiling Files That Use Assertions Enabling & Disabling Assertions

26 Enabling & Disabling Assertions By default, assertions are disabled. Enable assertions, using the -ea, switch. Disable assertions, using the -da, switch. Specify granularity as the switch argument: no arguments Enables/disables assertions in all classes except system classes. packageName... Enables/disables assertions in the package & any subpackages.... Enables/disables assertions in the unnamed package in the current working directory. className Enables/disables assertions in the named class.

27 Enabling & Disabling Assertions To run BatTutor, with assertions enabled in only package com.wombat.fruitbat & its subpackages: java -ea:com.wombat.fruitbat... BatTutor To run BatTutor with assertions: –enabled in package com.wombat.fruitbat –disabled in class com.wombat.fruitbat.Brickbat : java -ea:com.wombat.fruitbat... - da:com.wombat.fruitbat.Brickbat BatTutor

28 Enabling & Disabling Assertions To (en/dis)able system class assertions, use: -esa -dsa To run BatTutor with assertions: enabled in system classes, enabled in the com.wombat.fruitbat package & its subpackages: java -esa -ea:com.wombat.fruitbat... BatTutor