References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1
Assertions Statements about input to a routine or state of a class Have two primary roles As documentation, they express valid ways of using a routine or class When implemented, help to isolate runtime errors 10/14/2004 2
Assertions - Example public class SimpleStack { //Assertion: this method should only be called when the stack is not empty public int pop() { if (size() <= 0) { throw new Stackexception( pop() called on an empty stack ); return data[--top]; Implements the assertion //Assertion: this method returns the number of elements on the stack public int size() { return top; Documents the routine 10/14/2004 3
Assertions An unambiguous way to document a routine Can be checked at runtime Originally part of Java (then called Oak), but omitted from spec in order to meet deadline 10/14/2004 4
Assertions Popularized by Bertrand Meyer(1992) and directly supported by the language Eiffel. Boolean expressions attached to methods Test the state of an object at various points during execution, ensuring that certain conditions are satisfied Automatically inherited and enforced by subclasses even when actual methods are overridden 10/14/2004 5
Design by Contract Meyer proposed this idea: assertions form a contract between client and service provider software contracts are specified by pre- and post-conditions and class invariants Failure to meet the contract terms indicates a bug (fault) 10/14/2004 6
Design by Contract Violation of a pre-condition means the contract was broken by the client The contractor does not have to fulfill its part of the contract, but may raise an exception to signal the fault Violation of a post-condition indicates the presence of a bug in the implementation of the routine 10/14/2004 7
Preconditions A condition that must be true before a method executes Documents the assumptions of the author of the routine Clients of the method are responsible for ensuring the preconditions are met on entrance to the method; if they are not, then the method behavior is undefined Must be verifiable by the client using the public interface of the class that contains the method Client should be able to verify the preconditions from the current state of the object 10/14/2004 8
Preconditions public class BankAccount { public void deposit (float amount) {... Precondition is invalid: no way of verifying the precondition from the current state of the object //Pre-condition: amount <= current balance public void withdraw (float amount) {... This assumes that there is no method to return current balance. 10/14/2004 9
Postconditions Condition that will be true after a method executes Author of the method is responsible for ensuring the method s post-conditions are met Author of the method must only ensure the post-conditions of a method are true when the pre-conditions of the method have been met 10/14/2004 10
Postconditions May be expressed in terms of the public interface and/or the private implementation Post-condition expressed in terms of the public interface is of interest to clients Post-condition expressed in terms of the private interface is of interest to programmers maintaining the routine 10/14/2004 11
Invariants An invariant is an expression about an object that must be true when the object is in a stable state. An object is in a stable state after construction and between public method calls. pre- and post-conditions are statements about behavior of a method invariants are statements about state of an object. Because invariants are true after construction and between public method calls, the class is responsible for maintaining invariants. 10/14/2004 12
Invariants Also expressed in terms of the public interface and/or the private implementation True for the current public methods of a class and any new methods that are added in the future If a new public routine is allowed to violate an invariant, it may leave the object in an unstable state for another public method. 10/14/2004 13
Example // Invariant: 0 <= size() <= capacity() public class SimpleStack { // Pre-condition: The stack is not // empty // Post-condition: The last integer // pushed onto the stack is // returned. The stack size // is reduced by one // element. public int pop() { return data[--top]; // Pre-condition: <none> // Post-condition: The number of // elements in the stack are returned public int size() { return top; // Pre-condition: <none> // Post-condition: The capacity of // the stack is returned public int capacity() {... return capacity; Example showing a pre-condition, post-condition, and invariant. None of the assertions are checked at runtime. 10/14/2004 14
Pre- and Post-condition strength The strength of a pre- or post-condition is a measure of its restrictiveness. A strong pre- or post-condition is more restrictive than a weaker one. For example, a function that only accepts integers is more restrictive (has a stronger precondition) than one that accepts any real number. The weakest pre- or post-condition is no pre- or post-condition at all. 10/14/2004 15
Example 1: Binary Search public class Arrays {... // Pre-condition: the array 'a' is sorted in ascending //order // Post-condition: Returns the index of the first element in // array 'a' equal to 'key' if one exists, otherwise returns // -1 as an indication that the parameter 'key' is not an // element of the array. Duplicates allowed public static int binarysearch(int[] a, int key);... 10/14/2004 16
Example 2: Binary Search A stronger pre-condition is one that is more restrictive or narrows the range of acceptable inputs. The original definition of the binary search method allowed duplicate elements. The following is a stronger pre-condition: // Pre-condition: the array 'a' is sorted in // ascending order, and doesn't contain any // duplicate elements 10/14/2004 17
Example 3 : Binary Search We could weaken the post-condition of the original definition by allowing the routine to return any negative number if the key is not found: // Post-condition: Returns the index of the first // element in array 'a' equal to 'key' if one exists, // otherwise returns any negative number as an // indication that the parameter 'key' is not an // element of the array. This post-condition is weaker because there is a greater number of outputs that are valid. 10/14/2004 18
Strength of Assertions Reason for making the pre-condition stronger or the post-condition weaker than what the routine would suggest: Flexibility. A stronger pre-condition and a weaker postcondition give you the flexibility to change the implementation in the future without changing the interface and possibly breaking clients. Flexibility comes at the expense of the client. The client now has to work harder to maintain the pre-condition and to be prepared for the post-condition. 10/14/2004 19
Strength of Assertions When defining the pre- and post-conditions for a routine, need balance. Consider how much implementation flexibility is needed in the routine and how much additional burden it is for the client for a given amount of flexibility. Pre-conditions should be strong enough and postconditions should be weak enough to allow flexibility, but not too strong or too weak that it places an unreasonable burden on the client. 10/14/2004 20
Benefits of Assertion Checking Assertion checking at runtime is a debugging aid. The primary purpose of assertion checking at runtime is to identify and isolate runtime errors. Finding a runtime error in a large software system is difficult. The difficulty grows more than linearly with the size of the system. For example, if the size of a system doubles it will be more than twice as hard to find a runtime error. 10/14/2004 21
Benefits of Assertion Checking The fault (such as a wrong number on a report) is often a long distance from the defect (such as not reading the last record during the input loop). distance can be the number of instructions executed at runtime or physical distance between static instructions in the written program. The greater the distance between a fault and the defect the harder it will be to find a defect that caused a specific fault. The traditional way of debugging a problem is to start at the fault and work your way back to the defect. Because of conditional branching in code, as you work backwards the number of source branches you need to consider grows exponentially. 10/14/2004 22
Benefits of Assertion Checking In this conceptual image, there are 10 potential source paths for the visible fault. Assertion checking helps to identify errors early, closer to the defect that caused them. Assertion checking may identify errors that would have otherwise gone undetected. 10/14/2004 23
Mechanics of Assertion Checking There are no rigid rules for writing assertion checks. For example, the following is acceptable: // Pre-condition: a >= 0 public static double sqrt(double a) { if (a < 0) System.exit(0);... but not much better than no check at all, because it doesn't give any indication about the assertion that failed. 10/14/2004 24
Mechanics of Assertion Checking We can improve the previous example by adding an error message: // Pre-condition: a >= 0 public static double sqrt(double a) { if (a < 0) { System.out.println("Pre-condition failure in sqrt()."); System.out.println("Input is < 0."); System.exit(0);... Adding an error message makes it easier to find the problem that ended the program abnormally, but still may make it hard to locate the problem in a large program. 10/14/2004 25
Mechanics of Assertion Checking Another method to signal and find an error is to print a stack trace: // Pre-condition: a >= 0 public static double sqrt(double a) { if (a < 0) { new Throwable().printStackTrace(); System.exit(0);... The new statement creates but doesn't throw an exception. The exception is created in order to have access to the nonstatic method printstacktrace(). 10/14/2004 26
Mechanics of Assertion Checking Throwing an exception is an acceptable way of signaling an assertion violation; however, you should never throw a checked exception: // Pre-condition: a >= 0 public static double sqrt(double a) throws Exception { if (a < 0) { // Wrong way to signal an assertion violation throw new Exception("Pre-condition failure. Input is < 0.");... Throwing a checked exception forces the caller to check for the exception. Assertion code shouldn't require any modifications to the "real" code. Here "real" refers to the client code implementing the specifications of the application. 10/14/2004 27
Mechanics of Assertion Checking If assertion checking code throws an exception, it should be an unchecked exception: // Pre-condition: a >= 0 public static double sqrt(double a) { if (a < 0) { // Correct way to signal an assertion violation //with an exception throw new Error("Pre-condition failure. Input is < 0.");... 10/14/2004 28
Assertions in Java The Java API 1.4 now includes assertions. Here is what Sun says: Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors 10/14/2004 29
Java Assertions java.lang Class AssertionError java.lang.object +--java.lang.throwable +-- java.lang.error +--java.lang.assertionerror All Implemented Interfaces: Serializable 10/14/2004 30
Two forms of assertion statement simpler form: assert Expression1 ; boolean expression. where Expression1 is a When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message. second form: assert Expression1 : Expression2 ; where: Expression1 is a boolean expression. Expression2 is an expression that has a value. (cannot be an invocation of a method that is declared void.) 10/14/2004 31
Example usage use an assertion whenever you would have written a comment that asserts an invariant. For example: if (i % 3 == 0) {... else if (i % 3 == 1) {... else { assert i % 3 == 2 : i;... 10/14/2004 32
Mechanics of Assertion Checking Assertions can be added for some or all of the routines that have documented assertions. Pre-conditions are checked at the start of public and private routines. Post-conditions are checked at the end of public and private routines. Invariants are checked after constructors and at the start and end of public routines. 10/14/2004 33