Professional Documents
Culture Documents
MODULE: Correctness and Robustness: Correctness - " (The Software's) Ability To Perform
MODULE: Correctness and Robustness: Correctness - " (The Software's) Ability To Perform
MODULE: Correctness and Robustness: Correctness - " (The Software's) Ability To Perform
Robustness
Correctness – “[the software’s] ability to perform
according to specification”
javaprogrammering
Correctness
– How do we test (and measure) correctness?
Tools:
• Assertions – used for checking the current
property of software entities
• Tests – unit tests, test suites (also checks
robustness)
javaprogrammering
Assertions
• Assert – “hävda, påstå, försäkra, bedyra” (Stora
engelsk-svenska ordboken”, Esselte Studium)
javaprogrammering
Assertions
• Assertions can be used for checking pre-
conditions, post-conditions, and class invariant
javaprogrammering
Invariant, recap.
Invariant – “A rule, such as the ordering of an
ordered list or heap, that applies throughout the life
of a data structure or procedure. Each change to the
data structure must maintain the correctness of the
invariant”.
(http://foldoc.doc.ic.ac.uk/foldoc/index.html)
javaprogrammering
class MyStack {
Invariant, ex
private char[] cArr; // internal rep
private int i = 0;
.
.
void push(char c) {
cArr[i] = c;
i++;
}
}
javaprogrammering
Assertions in Java
public int myMethod(int x) {
assert (x>=0);
// ALT: assert (x>=0): “Negative input!”;
.
.
assert (y>=0);
assert invariantOK();
return y;
}
javaprogrammering
Correctness vs. Efficiency?
Assertions take time There is a trade-off
between correctness and efficiency
javaprogrammering
Design by Contract
“Design by contract”
vs.
“Defensive programming”
javaprogrammering
Design by Contract
A contract is a contract…so:
make the client responsible for the quality of input!
javaprogrammering
Design by Contract
Applies also at class- and package-level.
javaprogrammering
Handling assertions?
• It is possible to catch – and potentially recover
from – an assertion error.
• Should we do that?
– A string interactively provided by a user…
– A database call…
– An open remote connection…
javaprogrammering
Robustness
Robustness – “[the software’s] ability to react to
cases not included in the specification”
Tools:
Exception – “an abnormal [runtime] event that
disrupts execution”
Tests – unit tests, test suites (checks also
correctness)
javaprogrammering
Failure vs. exception
• Do exceptions always lead to failure…?
• We can often handle exceptions.
• Failure is the consequence of an unhandled exception.
• If an exception is not (cannot) be handled, the contract is
broken (routine does not terminate in a state satisfying
the contract)
• Exception – may happen
• Failure – should not happen
• deal with exceptions so that failure doesn’t happen!
javaprogrammering
Exception types
1. Checked exeptions – we can deal with these
during execution
javaprogrammering
Exceptions in Java
Throwable
RuntimeException ”unchecked”
javaprogrammering
Exception
• Checked exceptions
- IOException, SQLException, etc
- programmer-defined exceptions (inheriting from Exception)
• Errors
- OutOfMemoryError, ThreadDeathError osv
javaprogrammering
Unchecked exceptions, ex
for (int i=0; i<=10; i++) {
System.out.println(arr[i]);
}
• Throws an ArrayIndexOutOfBoundsException if
i>(arr.length-1)
• Throws a NullPointerException if an element (arr[i])
is null
• etc.
javaprogrammering
Checked exeptions, ex
try{
// dangerous code here
.
.
}catch ( MyException me ){
// try to recover or
// give notification
}
javaprogrammering
Throwing exceptions, ex
class Dangerous{
public void dangerousCode()
throws MyException, MyOtherException {
if (someCondition){
throw new MyException();
}else{
throw new MyOtherException ();
}
}
}
javaprogrammering
Checked exeptions, ex
try{
File f = new File(fName);
FileReader fr = new FileReader(f);
char c = fr.read();
.
.
}catch (NullPointerException npe ){
// no file name (fName is null)
}catch (FileNotFoundException fnfe ){
// try another file…?
}catch (IOException ioe ){
// couldnt read…
}
javaprogrammering
File f = null; finally, ex
FileReader fr = null;
try{
f = new File(fName);
fr = new FileReader(f);
char c = fr.read();
.
}catch (IOException ioe ){
// some IO error…
} finally {
try { if (fr!=null) fr.close();
} catch (IOException ie) {
// couldn’t close!
}
} javaprogrammering
mySqrt() again…
public float mySqrt(float f) {
assert (f>=0);
float result = 0.0; redundancy!
if (f>=0) {
result = (float) Math.sqrt(f);
} else {
throw new IllegalArgumentException(“negative!”);
}
return result;
}
javaprogrammering
Assertions vs. exceptions
• Assertions should never be checked – they always
mark a broken contract.
• Practical consideration:
– Assertions can be easily de-activated.
javaprogrammering
A way to get fired…
Why could you loose friends and work for this…?
try {
// do dangerous stuff here
} catch (Exception e) { }
javaprogrammering
To catch or not to catch?
try {
while (i<maxIndx) { System.out.println(arr[i++]); }
} catch (ArrayIndexOutOfBoundsException aiobe) {
// i is out of bounds - do what?
}
try { myObj.myMethod(); }
} catch (NullPointerException npe) {
// myObj is null - do what?
}
javaprogrammering
Exceptions and program structure
Do the users really want to see exceptions?
Integration
DB-related exceptions
DB
javaprogrammering
Re-throwing exceptions
try {
log(se);
throw new bank.TechnicalException(
“Persistency error”);
javaprogrammering
MODULE: I/O
• File
• Byte streams
• Character streams
• Serialization
javaprogrammering
java.io.File
boolean canRead()
boolean canWrite()
boolean delete()
boolean exist()
String getAbsolutePath()
String getName()
boolean isDictory()
boolean isFile()
long lastModified()
boolean mkDir()
boolean renameTo()
javaprogrammering
Byte streams
InputStream
FileInputStream
PipedInputStream
ByteArrayInputStream
javaprogrammering
Character streams
Reader
InputStreamReader
BufferedReader
PipedReader
FileReader
javaprogrammering
Chaining
• What if we want to read characters from a text file?
• Build your own reader!
• You need:
– File – abstract representation of a file (or directory)
– FileInputStream – obtains bytes from a file
– InputStreamReader – a bridge from byte- to character
streams
– BufferedReader – reads and buffers text from a
character stream
javaprogrammering
InputStreamReader
Chaining
FileInputStream BufferedReader
File
program
javaprogrammering
Chaining, ex
import java.io.*;
.
.
String readStringFromFile() throws IOException {
String s = null;
File f = new File(“a_file_name”);
FileInputStream fs = new FileInputStream(f);
InputStreamReader ir = new InputStreamReader(fs);
BufferedReader br = new BufferedReader(ir);
s = br.readLine();
br.close();
return s;
}
javaprogrammering
System.in, System.out, System.err
• The class java.lang.System has three static attributes with
references to standard streams:
javaprogrammering
Saving objects
• Use serialization to save the current state of an object.
javaprogrammering
Serialisering
Person String
String name ”Sture”
int phoneNo 08-555 1066
Address address
String
Address ”Bättringsvägen 13”
String street
String city String
int zip 555 55 ”Sunksvall”
javaprogrammering
Writing an object, ex
• Write using java.io.ObjectOutputStream:
Person p = new Person();
try{
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(”ettPersonObj.ser”));
oos.writeObject(p);
}catch(IOException ioe){
ioe.printStackTrace();
}
javaprogrammering
Reading an object, ex
• Read using java.io.ObjectInputStream:
try{
ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("ettPersonObj.ser"));
Object o = ois.readObject(); // read as object
Person p =(Person) o; // explicit cast to Person
}catch(IOException ioe){
ioe.printStackTrace();
}catch(ClassNotFoundException cnfe){
ioe.printStackTrace();
}
javaprogrammering
transient
• We don’t always want to save all kinds of
attributes, e.g.:
javaprogrammering
Exercise, bank 3
• Save the bank system on disk
– (when shutting down, save current state first)
javaprogrammering
This document was created with Win2PDF available at http://www.daneprairie.com.
The unregistered version of Win2PDF is for evaluation or non-commercial use only.