490 likes | 497 Views
Learn about algorithm correctness and efficiency in CIS 068 with topics including program defects, exceptions, testing strategies, formal methods of verification, and efficiency of algorithms.
E N D
Welcome to CIS 068 ! Lesson 3: Algorithm Correctness And Efficiency CIS 068
Overview • Subjects: • Program Defects • Exceptions • Testing Strategies • Formal Methods of Verification • Efficiency of Algorithms CIS 068
Errors • Three kinds of errors: • Syntax errors • Runtime errors • Logical errors CIS 068
Syntax Errors • Mistakes in the use of language‘s grammar (or syntax) • Usually not critical • Usually discovered by compiler • ...but sometimes hard to find ! CIS 068
Syntax Error Example • The next slide will show a JAVA program. It is supposed to show all numbers n divisible by 7 without remainder, 0<n<1000 • Please answer the following questions: • Will the compiler accept the code ? • What is the program‘s result ? • Does a compiler always find syntax-errors ? CIS 068
Syntax Error Example • public class Class1 • { • public static void main(String[] args) • { • /* Detect if number is multiple of 7 */ • for (int i=1; i<1000; i++){ • if ((i%7) == 0){ • System.out.println(i+""); • // Exit Program --------------------------------- • System.out.println("That's it. Goodbye."); • System.exit(0); • } • } • } • } The loop is defined by these brackets ! The program will exit INSIDE the loop CIS 068
Syntax Error Example • Will the compiler accept the code ? • What is the program‘s result ? • Does a compiler always find syntax-errors ? YES “That’s it. Goodbye” NO ! CIS 068
Runtime Errors • Occuring during program execution • Critical if appearing in special cases (see Example ‘AT&T breakdown’, last lesson) • Not discovered by compiler • Forces the computer to exit program (if no recovery code is written) CIS 068
Runtime Error Example • The next slide will show a JAVA program, assigning the series 1,1/2, 1/3, 1, 1/2, 1/3,... to a 60-element array. • Please answer the following questions: • Will the compiler accept the code ? • What will happen executing the program ? CIS 068
Runtime Error Example • public class Class1 • { • public static void main(String[] args) • { • int myArray[] = new int[60]; • // Assign 1, ½, 1/3, 1, ½, 1/3... to myArray • for (int i =1; i <= 60; i++){ • myArray[i] = i/(i%3); • } • } • } Index out of bounds (60) Expression (i%3) is 1,2,0,1,2,0.. Division by Zero ! CIS 068
Runtime Error Example • Will the compiler accept the code ? • What will happen executing the program ? Yes (Multiple) Runtime Errors will occur, starting with a division by zero. CIS 068
Common Runtime Errors CIS 068
Common Runtime Errors cont‘d • Class Cast Exception • References to objects of one type can be casted to different types in the class-hierarchy • Two types of casting: • UPcasting • DOWNcasting CIS 068
Up/Down casting Root UPCAST Always safe Can cause error Derived from DOWNCAST class1 CIS 068
Up/Down casting Example: • Class2 derived from Class1 • Class2 adds field int onlyInClass2 CIS 068
Up/Down casting, examples Class1 c1 = new Class1(); // c1 = Class1 - Object Class2 c2 = new Class2(); // c2 = Class2 - Object // Class2 c3 = (Class2)c1; // DOWNCAST ERROR ! // Class1 c3 = (Class1)c2; // UPCAST ((Class2)c3).onlyInClass2 = 5; // DOWNCAST possible ! // Class1 c3 = c1; ((Class2)c3).onlyInClass2 = 5; // DOWNCAST ERROR ! CIS 068
NullPointerError • Occurs when trying to attempt a non-existing object • For C++ - programmers: don’t be confused, there are really no pointers in JAVA ! Example: Object testObject = null; // init Object to null (necessary for compiler) If (expression) { // testObject = new Object (); // create Object } testObject.testMethod(); // will result in error if expression was false CIS 068
Exceptions How to handle errors Without exceptions: • program entered undefined state or crashes • possible errors can be guarded by if – statements • better use exceptions ! CIS 068
Exceptions Are The Rule Runtime Error Create instance of class Exception (‘throw’ exception) Program ‘catches’ the exception, i.e. appropriate codeblock is entered CIS 068
Try – Catch mechanism Syntax: try { // Statements that may throw exceptions … } catch(Exception1 e1){ //statements to execute for exceptions type Exception1 } catch(Exception2 e2){ //statements to execute for exceptions type Exception2 } … finally{ // Statements to execute after try-catch } CIS 068
Try – Catch Example try{ int n = 4 / 0; } catch(ArithmeticException ae){ ae.printStackTrace(); } Some Exceptions provided by JAVA: CIS 068
Exceptions Exceptions are Objects Since Exceptions are Objects, you can derive your own Exception. myOwnException CIS 068
Exceptions What to do with exceptions ? • every exception has the methods • getMessage(), returning a detailed message of the exception • printStackTrace(), printing the exception and its backtrace • getMessage() and printStackTrace() are inherited from class Throwable CIS 068
Exceptions Example: try{ … } catch(Exception e){ System.out.println(e.getMessage()); e.printStackTrace(); } … Example for Stack-Trace: CIS 068
Exceptions try – catch – finally • finally {} is ALWAYS executed independent from execution of try{} and/or catch {} – body • Only System.exit() overrides that rule • A good place to clean up ! CIS 068
Throwing Exceptions Using the throw – command, Exceptions can directly be triggered (rather than waiting for the JVM) CIS 068
Logic Errors Most Critical Errors Occur in the design – phase Can’t be detected by computer, not at compile-time, not at run-time What can be done ? CIS 068
Logic Errors carefully check the algorithm single step tracing explain and simulate execution with other team members (structured walkthrough) use program testing strategies CIS 068
Testing Strategies Develop test-plan early in the design stage CIS 068
Testing Strategies • Use defensive programming, i.e. include code for every unexpected or invalid data values ! (Example: string – input) CIS 068
Testing Strategies Testing questions: • Who does the testing ? • Blackbox or Whitebox – Testing ? CIS 068
Testing Strategies Top – Down Testing • Entire logical flow is implemented • Usage of stubs instead of completed Methods • Easy to write • provide defined results • easy simulation of unexpected data CIS 068
Testing Strategies Bottom – Up Testing • implementation of single methods • test of each method separately by driver - programs CIS 068
Debugging Tips Carefully document each method parameter and local variable using comments as you write the code. Also describe the method’s purpose. Name methods and variables meaningful Create an execution-trace by printing out the method’s name when executed Display the values of all arguments upon entry to a method Display the values of all results after returning from a method Verify results by hand – computation ! CIS 068
Formal Methods of Program Verification Assertions • logical statements about the program which are asserted to be true • written as a comment in the code to describe what is supposed to be true at this point • task of tester: prove that a program fragment meets its specification CIS 068
Assertions A simple example Proving means: the final assertion, the postcondition, follows from the initial precondition CIS 068
Assertions The assignment rule: testing vice versa • allows to transform a postcondition in a precondition • Replace each occurrence of x in R with e • Truth of x after the assignment is given by truth of e prior to the assignment CIS 068
Assertions Verifying an if – statement Formally: CIS 068
Assertions Verifying an if – statement Example: CIS 068
Assertions Verifying Loops: Loop Invariants • Logical statement involving program variables that is true • before the loop is entered • after each execution of the loop body • when the loop termination occurs The loop – invariant ‘simulates’ a constant precondition CIS 068
Loop Invariants - Example CIS 068
Loop Invariants - Example CIS 068
Loop Invariants - Example (example 2) CIS 068
Efficiency • Measurement of number of program – steps performed • Usually a precise measure can’t be given • Approximation dependent on preconditions • Big – O (Order of Magnitude) Notation CIS 068
Big – O Notation Definition: Algorithm has order of magnitude f(n) [=O(f(n))] means: There exists a constant C such that the actual running-time T(N) is less than C * f(n) for N towards infinity f(n) can therefore be determined by the fastest growing term of the algorithm. CIS 068
Big – O Notation Example: An algorithm performing n*n + 4 steps (depending on precondition n) has the order of magnitude n*n, O(n*n) Question: Is an O(n) algorithm A1 necessarily always (i.e. for all n) faster than an O(n*n) algorithm A2 ? CIS 068
Big – O Notation (example: insert) CIS 068
Review Subjects: • Different Types of Errors • Exceptions, try-catch-finally • Testing Strategies • Formal Methods of Verification • assignment rule • loop invariants • Efficiency of Algorithms • Big O CIS 068
Good Bye The Subjects of this lesson are covered in chapter 2 of Software Design & Data Structures in Java By Elliot B. Koffman + Paul A. T. Wolfgang CIS 068