Transcript Document

Welcome to CIS 068 !
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:
1. Syntax errors
2. Runtime errors
3. 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
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
Index out of bounds (60)
{
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++){
Expression (i%3) is 1,2,0,1,2,0..
myArray[i] = i/(i%3);
}
}
}
Division by Zero !
CIS 068
Runtime Error Example
• Will the compiler accept the code ?
Yes
• What will happen executing the program ?
(Multiple) Runtime Errors will occur,
starting with a division by zero.
CIS 068
Common Runtime Errors
CIS 068
NullPointerError
• Occurs when trying to attempt a nonexisting object
• For C++ - programmers: don’t be
confused, there are really no pointers in
JAVA !
Example:
Object testObject ;
// init Object (to null )
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
• ALWAYS means: even after a possible
return statement in either try or catch block !
This is especially useful if there are multiple
exit (return) points.
• 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 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:
1.
Will the compiler accept the code ?
2.
What is the program‘s result ?
3.
Does a compiler always find syntax-errors ?
CIS 068
Syntax Error Example
public class Class1
{
public static void main(String[] args)
{
The loop is defined by these brackets !
/* 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 program will exit INSIDE the loop
}
}
}
CIS 068
Logic Error Example
•
Will the compiler accept the code ?
YES
•
What is the program‘s result ?
“That’s it. Goodbye”
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 !
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
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
Review
Subjects:
• Different Types of Errors
• Exceptions, try-catch-finally
• Testing Strategies
•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