program correctness and efficiency - montana state univsrgurram/crap/221-ch02.pdf · the java...
Post on 03-Jul-2018
224 Views
Preview:
TRANSCRIPT
Chapter ObjectivesChapter Objectives
To understand the differences between the three categories of program errorsTo understand the effect of an uncaught exception and why you should catch exceptionsTo become familiar with the Exception hierarchy and the difference between checked and unchecked exceptionsTo learn how to use the try-catch-finally sequence to catch and process exceptionsTo understand what it means to throw an exception and how to throw an exception in a method
To understand the differences between the three categories of program errorsTo understand the effect of an uncaught exception and why you should catch exceptionsTo become familiar with the Exception hierarchy and the difference between checked and unchecked exceptionsTo learn how to use the try-catch-finally sequence to catch and process exceptionsTo understand what it means to throw an exception and how to throw an exception in a method
Chapter Objectives (continued)Chapter Objectives (continued)
To understand the different testing strategies and when and how they are performedTo learn how to write special methods to test other methods and classesTo become familiar with debugging techniques and debugger programsTo be introduced to the process of program verification and the use of assertions and loop invariantsTo understand the meaning of big-O notation and how it is used to analyze an algorithm’s efficiency
To understand the different testing strategies and when and how they are performedTo learn how to write special methods to test other methods and classesTo become familiar with debugging techniques and debugger programsTo be introduced to the process of program verification and the use of assertions and loop invariantsTo understand the meaning of big-O notation and how it is used to analyze an algorithm’s efficiency
Program Defects and “Bugs”Program Defects and “Bugs”
A program may be efficient, but is worthless if it produces a wrong answerDefects often appear in software after it is deliveredTesting can never demonstrate the complete absence of defectsIn some situations it is very difficult to test a software product completely in the environment in which it is usedDebugging: removing defects
A program may be efficient, but is worthless if it produces a wrong answerDefects often appear in software after it is deliveredTesting can never demonstrate the complete absence of defectsIn some situations it is very difficult to test a software product completely in the environment in which it is usedDebugging: removing defects
Syntax ErrorsSyntax Errors
Syntax errors are mistakes in the grammar of a languageThe Java compiler detects syntax errors during compilation and requires you to correct them before successfully compiling the programSome common syntax errors include:
Omitting or misplacing bracesPerforming an incorrect type of operation on a primitive type valueInvoking an instance method not defined Not declaring a variable before using itProviding multiple declarations of a variable
Syntax errors are mistakes in the grammar of a languageThe Java compiler detects syntax errors during compilation and requires you to correct them before successfully compiling the programSome common syntax errors include:
Omitting or misplacing bracesPerforming an incorrect type of operation on a primitive type valueInvoking an instance method not defined Not declaring a variable before using itProviding multiple declarations of a variable
Run-time Errors or ExceptionsRun-time Errors or Exceptions
Run-time errorsOccur during program executionOccur when the JVM detects an operation that it knows to be incorrectCause the JVM to throw an exception
Examples of run-time errors includeDivision by zeroArray index out of boundsNumber format and Input mismatch errorNull pointer exceptions
Run-time errorsOccur during program executionOccur when the JVM detects an operation that it knows to be incorrectCause the JVM to throw an exception
Examples of run-time errors includeDivision by zeroArray index out of boundsNumber format and Input mismatch errorNull pointer exceptions
Logic ErrorsLogic Errors
A logic error occurs when the programmer or analystMade a mistake in the design of a class or methodImplemented an algorithm incorrectly
Most logic errors do not cause syntax or run-time errors and are thus difficult to findSometimes found through testingSometimes found during real-world operation of the program
A logic error occurs when the programmer or analystMade a mistake in the design of a class or methodImplemented an algorithm incorrectly
Most logic errors do not cause syntax or run-time errors and are thus difficult to findSometimes found through testingSometimes found during real-world operation of the program
The Exception Class HierarchyThe Exception Class Hierarchy
When an exception is thrown, one of the Java exception classes is instantiatedExceptions are defined within a class hierarchy that has the class Throwable as its superclassClasses Error and Exception are subclasses of ThrowableRuntimeException is a subclass of Exception
When an exception is thrown, one of the Java exception classes is instantiatedExceptions are defined within a class hierarchy that has the class Throwable as its superclassClasses Error and Exception are subclasses of ThrowableRuntimeException is a subclass of Exception
The Class ThrowableThe Class Throwable
Throwable is the superclass of all exceptionsAll exception classes inherit the methods of throwableThrowable is the superclass of all exceptionsAll exception classes inherit the methods of throwable
Checked and Unchecked ExceptionsChecked and Unchecked Exceptions
Two categories of exceptions: checked and uncheckedChecked exception normally not due to programmer error and is beyond the control of the programmerUnchecked exception may result from
Programmer errorSerious external conditions that are unrecoverable
Two categories of exceptions: checked and uncheckedChecked exception normally not due to programmer error and is beyond the control of the programmerUnchecked exception may result from
Programmer errorSerious external conditions that are unrecoverable
Catching and Handling ExceptionsCatching and Handling Exceptions
When an exception is thrown, the normal sequence of execution is interruptedDefault behavior
Program stopsJVM displays an error message
The programmer may override the default behavior byEnclosing statements in a try blockProcessing the exception in a catch block
When an exception is thrown, the normal sequence of execution is interruptedDefault behavior
Program stopsJVM displays an error message
The programmer may override the default behavior byEnclosing statements in a try blockProcessing the exception in a catch block
Uncaught ExceptionsUncaught Exceptions
When an exception occurs that is not caught, the program stops and the JVM displays an error message and a stack traceThe stack trace shows the sequence of method calls, starting at the method that threw the exception and ending at main
When an exception occurs that is not caught, the program stops and the JVM displays an error message and a stack traceThe stack trace shows the sequence of method calls, starting at the method that threw the exception and ending at main
The try-catch-finally SequenceThe try-catch-finally Sequence
Avoid uncaught exceptionsWrite a try-catch sequence to catch an exceptionHandle it rather than relying on the JVM
Catch block is skipped if all statements within the try block execute without error
Avoid uncaught exceptionsWrite a try-catch sequence to catch an exceptionHandle it rather than relying on the JVM
Catch block is skipped if all statements within the try block execute without error
Handling Exceptions to Recover from Errors
Handling Exceptions to Recover from Errors
Exceptions provide the opportunity toRecover from errorsReport errors
User error is a common source of error and should be recoverableCatch block within the first catch clause having an appropriate exception class executes, others are skippedCompiler displays an error message if it encounters an unreachable catch clause
Exceptions provide the opportunity toRecover from errorsReport errors
User error is a common source of error and should be recoverableCatch block within the first catch clause having an appropriate exception class executes, others are skippedCompiler displays an error message if it encounters an unreachable catch clause
The finally BlockThe finally Block
When an exception is thrown, the flow of execution is suspended and there is no return to the try blockThere are situations in which allowing a program to continue after an exception could cause problemsThe code in the finally block is executed either after the try block is exited or after a catch clause is exitedThe finally block is optional
When an exception is thrown, the flow of execution is suspended and there is no return to the try blockThere are situations in which allowing a program to continue after an exception could cause problemsThe code in the finally block is executed either after the try block is exited or after a catch clause is exitedThe finally block is optional
Throwing ExceptionsThrowing Exceptions
Instead of catching an exception in a lower-level method, it can be caught and handled by a higher-level method
Declare that the lower-level method may throw a checked exception by adding a throws clause to the method headerCan throw the exception in the lower-level method, using a throw statement
The throws clause is useful if a higher-level module already contains a catch clause for this exception type
Instead of catching an exception in a lower-level method, it can be caught and handled by a higher-level method
Declare that the lower-level method may throw a checked exception by adding a throws clause to the method headerCan throw the exception in the lower-level method, using a throw statement
The throws clause is useful if a higher-level module already contains a catch clause for this exception type
Throwing Exceptions (continued)Throwing Exceptions (continued)
Can use a throw statement in a lower-level method to indicate that an error condition has been detectedOnce the throw statement executes, the lower-level method stops executing immediately
Can use a throw statement in a lower-level method to indicate that an error condition has been detectedOnce the throw statement executes, the lower-level method stops executing immediately
Programming StyleProgramming StyleYou can always avoid handling exceptions by declaring that they are thrown, or throwing them and letting them be handled farther back in the call chainIt is usually best to handle the exception instead of passing italongThe following are recommended guidelines:
If an exception is recoverable in the current method, handle the exception in the current methodIf a checked exception is likely to be caught in a higher-level method, declare that it can occur using a throws clauseIt is not necessary to use a throws clause with unchecked exceptions
You can always avoid handling exceptions by declaring that they are thrown, or throwing them and letting them be handled farther back in the call chainIt is usually best to handle the exception instead of passing italongThe following are recommended guidelines:
If an exception is recoverable in the current method, handle the exception in the current methodIf a checked exception is likely to be caught in a higher-level method, declare that it can occur using a throws clauseIt is not necessary to use a throws clause with unchecked exceptions
Testing ProgramsTesting Programs
There is no guarantee that a program that is syntax and run-time error free will also be void of logic errorsThe “best” situation is a logic error that occurs in a part of the program that always executes; otherwise, it may be difficult to find the errorThe worst kind of logic error is one that occurs in an obscure part of the code (infrequently executed)
There is no guarantee that a program that is syntax and run-time error free will also be void of logic errorsThe “best” situation is a logic error that occurs in a part of the program that always executes; otherwise, it may be difficult to find the errorThe worst kind of logic error is one that occurs in an obscure part of the code (infrequently executed)
Structured WalkthroughsStructured Walkthroughs
Most logic errors arise during the design phase and are the result of an incorrect algorithmLogic errors may also result from typographical errors that do not cause syntax or run-time errorsOne form of testing is hand-tracing the algorithm before implementingStructured walkthrough: designer must explain the algorithm to other team members and simulate its execution with other team members looking on
Most logic errors arise during the design phase and are the result of an incorrect algorithmLogic errors may also result from typographical errors that do not cause syntax or run-time errorsOne form of testing is hand-tracing the algorithm before implementingStructured walkthrough: designer must explain the algorithm to other team members and simulate its execution with other team members looking on
Levels and Types of TestingLevels and Types of Testing
Testing: exercising a program under controlled conditions and verifying the resultsPurpose is to detect program defects after all syntax errors have been removed and the program compilesNo amount of testing can guarantee the absence of defects in sufficiently complex programsUnit testing: checking the smallest testable piece of the software (a method or class)Integration testing: testing the interactions among units
Testing: exercising a program under controlled conditions and verifying the resultsPurpose is to detect program defects after all syntax errors have been removed and the program compilesNo amount of testing can guarantee the absence of defects in sufficiently complex programsUnit testing: checking the smallest testable piece of the software (a method or class)Integration testing: testing the interactions among units
Levels and Types of Testing (continued)
Levels and Types of Testing (continued)
System testing: testing the program in contextAcceptance testing: system testing designed to show that the program meets its functional requirementsBlack-box testing: tests the item based on its interfaces and functional requirementsWhite-box testing: tests the software with the knowledge of its internal structure
System testing: testing the program in contextAcceptance testing: system testing designed to show that the program meets its functional requirementsBlack-box testing: tests the item based on its interfaces and functional requirementsWhite-box testing: tests the software with the knowledge of its internal structure
Preparations for TestingPreparations for Testing
A test plan should be developed early in the design phaseAspects of a test plan include deciding how the software will be tested, when the tests will occur, who will do the testing, and what test data will be usedIf the test plan is developed early, testing can take place concurrently with the design and codingA good programmer practices defensive programming and includes code to detect unexpected or invalid data
A test plan should be developed early in the design phaseAspects of a test plan include deciding how the software will be tested, when the tests will occur, who will do the testing, and what test data will be usedIf the test plan is developed early, testing can take place concurrently with the design and codingA good programmer practices defensive programming and includes code to detect unexpected or invalid data
Testing Tips for Program SystemsTesting Tips for Program Systems
Most of the time, you will test program systems that contain collections of classes, each with several methodsIf a method implements an interface, its specification should document input parameters and expected resultsCarefully document each method parameter and class attribute using comments as you write the codeLeave a trace of execution by displaying the method name as you enter itDisplay values of all input parameters upon entry to a method
Most of the time, you will test program systems that contain collections of classes, each with several methodsIf a method implements an interface, its specification should document input parameters and expected resultsCarefully document each method parameter and class attribute using comments as you write the codeLeave a trace of execution by displaying the method name as you enter itDisplay values of all input parameters upon entry to a method
Testing Tips for Program Systems (continued)
Testing Tips for Program Systems (continued)
Display the values of any class attributes that are accessed by this methodDisplay the values of all method outputs after returning from a methodPlan for testing as you write each module rather than after the fact
Display the values of any class attributes that are accessed by this methodDisplay the values of all method outputs after returning from a methodPlan for testing as you write each module rather than after the fact
Developing the Test DataDeveloping the Test Data
Test data should be specified during the analysis and design phases for the different levels of testing: unit, integration, and systemIn black-box testing, we are concerned with the relationship between the unit inputs and outputs
There should be test data to check for all expected inputs as well as unanticipated data
In white-box testing, we are concerned with exercising alternative paths through the code
Test data should ensure that all if statement conditions will evaluate to both true and false
Test data should be specified during the analysis and design phases for the different levels of testing: unit, integration, and systemIn black-box testing, we are concerned with the relationship between the unit inputs and outputs
There should be test data to check for all expected inputs as well as unanticipated data
In white-box testing, we are concerned with exercising alternative paths through the code
Test data should ensure that all if statement conditions will evaluate to both true and false
Testing Boundary ConditionsTesting Boundary Conditions
When hand-tracing through an algorithm or performing white-box testing, you must exercise all paths Check special cases called boundary conditions
When hand-tracing through an algorithm or performing white-box testing, you must exercise all paths Check special cases called boundary conditions
Why do Testing?Why do Testing?
Normally testing is done byThe programmerOther members of the software team who did not code the module being testedFinal users of the software product
Do not rely on programmers for testing as they are often blind to their own oversightsCompanies also have quality assurance organizations that verify that the testing process is performed correctlyIn extreme programming, programmers work in pairs where one writes the code and the other writes the tests
Normally testing is done byThe programmerOther members of the software team who did not code the module being testedFinal users of the software product
Do not rely on programmers for testing as they are often blind to their own oversightsCompanies also have quality assurance organizations that verify that the testing process is performed correctlyIn extreme programming, programmers work in pairs where one writes the code and the other writes the tests
StubsStubs
It may be difficult to test a method or class that interacts with other methods or classesThe replacement of a method that has not yet been implemented or tested is called a stubA stub has the same header as the method it replaces, but its body only displays a message indicating that the stub was called
It may be difficult to test a method or class that interacts with other methods or classesThe replacement of a method that has not yet been implemented or tested is called a stubA stub has the same header as the method it replaces, but its body only displays a message indicating that the stub was called
DriversDrivers
A driver program declares any necessary object instances and variables, assigns values to any of the method’s inputs, calls the method, and displays the values of any outputs returned by the methodYou can put a main method in a class to serve as the test driver for that class’s methods
A driver program declares any necessary object instances and variables, assigns values to any of the method’s inputs, calls the method, and displays the values of any outputs returned by the methodYou can put a main method in a class to serve as the test driver for that class’s methods
Using a Test FrameworkUsing a Test Framework
A test framework is a software product that facilitates writing test cases, organizing the test cases into test suites, running the test suites, and reporting the resultsA test framework often used for Java products is JUnit, an open-source product that can be used in a stand-alone mode and is available from junit.org
A test framework is a software product that facilitates writing test cases, organizing the test cases into test suites, running the test suites, and reporting the resultsA test framework often used for Java products is JUnit, an open-source product that can be used in a stand-alone mode and is available from junit.org
“BUGS”“BUGS”
IMPORTANT NOTICE!YOU PUT EVERY BUG THE PROGRAM YOU WROTE!They DID NOT “Crawl In” from outside.
IMPORTANT NOTICE!YOU PUT EVERY BUG THE PROGRAM YOU WROTE!They DID NOT “Crawl In” from outside.
Debugging a ProgramDebugging a Program
Debugging is the major activity performed by programmers during the testing phaseTesting determines if there is an error, debugging determines the cause of itDebugging is like detective work
Inspect carefully the information displayed by your programInsert additional diagnostic output statements in the method to determine more information
Debugging is the major activity performed by programmers during the testing phaseTesting determines if there is an error, debugging determines the cause of itDebugging is like detective work
Inspect carefully the information displayed by your programInsert additional diagnostic output statements in the method to determine more information
Using a DebuggerUsing a Debugger
Debuggers often are included with IDEsA debugger can execute your program incrementally rather than all at onceSingle-step execution executes in increments as small as one program statementBreakpoints are used to traverse large portions of code before stoppingThe actual mechanics of using a debugger depend on the IDE that you are using
Debuggers often are included with IDEsA debugger can execute your program incrementally rather than all at onceSingle-step execution executes in increments as small as one program statementBreakpoints are used to traverse large portions of code before stoppingThe actual mechanics of using a debugger depend on the IDE that you are using
Reasoning about Programs: Assertions and Loop Invariants
Reasoning about Programs: Assertions and Loop Invariants
Assertions: logical statements about a program that are claimed to be true; generally written as a commentPreconditions and postconditions are assertionsA loop invariant is an assertion
Helps prove that a loop meets it specificationTrue before loop begins, at the beginning of each repetition of the loop body, and just after loop exit
Assertions: logical statements about a program that are claimed to be true; generally written as a commentPreconditions and postconditions are assertionsA loop invariant is an assertion
Helps prove that a loop meets it specificationTrue before loop begins, at the beginning of each repetition of the loop body, and just after loop exit
Efficiency of AlgorithmsEfficiency of Algorithms
Difficult to get a precise measure of the performance of an algorithm or programCan characterize a program by how the execution time or memory requirements increase as a function of increasing input size
Big-O notationA simple way to determine the big-O of an algorithm or program is to look at the loops and to see whether the loops are nested
Difficult to get a precise measure of the performance of an algorithm or programCan characterize a program by how the execution time or memory requirements increase as a function of increasing input size
Big-O notationA simple way to determine the big-O of an algorithm or program is to look at the loops and to see whether the loops are nested
Efficiency of Algorithms (continued)
Efficiency of Algorithms (continued)
Consider:
First time through outer loop, inner loop is executed n-1 times; next time n-2, and the last time once.So we have
T(n) = 3(n – 1) + 3(n – 2) + … + 3 orT(n) = 3(n – 1 + n – 2 + … + 1)
Consider:
First time through outer loop, inner loop is executed n-1 times; next time n-2, and the last time once.So we have
T(n) = 3(n – 1) + 3(n – 2) + … + 3 orT(n) = 3(n – 1 + n – 2 + … + 1)
Efficiency of Algorithms (continued)
Efficiency of Algorithms (continued)
We can reduce the expression in parentheses to:n x (n – 1)
2So, T(n) = 1.5n2 – 1.5nThis polynomial is zero when n is 1. For values greater than 1, 1.5n2 is always greater than 1.5n2 – 1.5nTherefore, we can use 1 for n0 and 1.5 for c to conclude that T(n) is O(n2)
We can reduce the expression in parentheses to:n x (n – 1)
2So, T(n) = 1.5n2 – 1.5nThis polynomial is zero when n is 1. For values greater than 1, 1.5n2 is always greater than 1.5n2 – 1.5nTherefore, we can use 1 for n0 and 1.5 for c to conclude that T(n) is O(n2)
Chapter ReviewChapter Review
Three kinds of defects can occur in programsSyntax errorsRun-time errorsLogic errors
All exceptions in the Exception class hierarchy are derived from a common superclass called ThrowableThe default behavior for exceptions is for the JVM to catch them by printing an error message and a call stack trace and then terminating the program
Three kinds of defects can occur in programsSyntax errorsRun-time errorsLogic errors
All exceptions in the Exception class hierarchy are derived from a common superclass called ThrowableThe default behavior for exceptions is for the JVM to catch them by printing an error message and a call stack trace and then terminating the program
Chapter Review (continued)Chapter Review (continued)
Two categories of exceptions: checked and uncheckedA method that can throw a checked exception must either catch it or declare that it is thrown“throw” statement throws an unchecked exceptionProgram testing is done at several levels starting with the smallest testable piece of a program called a unitIntegration testing: once units are individually tested, they can then be tested togetherSystem testing: once the whole program is put together, it is tested as a whole
Two categories of exceptions: checked and uncheckedA method that can throw a checked exception must either catch it or declare that it is thrown“throw” statement throws an unchecked exceptionProgram testing is done at several levels starting with the smallest testable piece of a program called a unitIntegration testing: once units are individually tested, they can then be tested togetherSystem testing: once the whole program is put together, it is tested as a whole
Chapter Review (continued)Chapter Review (continued)
Acceptance programming involves testing in an operational manner demonstrating its functionalityBlack-box testing tests the item based on its functional requirements without knowledge of its internal structureWhite-box testing tests the item using knowledge of its internal structureTest drivers and stubs are tools used in testing
Test drivers exercise a method or class Stubs stand in for called methods
Big-O notation determines the efficiency of a program
Acceptance programming involves testing in an operational manner demonstrating its functionalityBlack-box testing tests the item based on its functional requirements without knowledge of its internal structureWhite-box testing tests the item using knowledge of its internal structureTest drivers and stubs are tools used in testing
Test drivers exercise a method or class Stubs stand in for called methods
Big-O notation determines the efficiency of a program
top related