MODULE: Correctness and Robustness: Correctness - " (The Software's) Ability To Perform

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

MODULE: Correctness and

Robustness
Correctness – “[the software’s] ability to perform
according to specification”

Robustness – “[the software’s] ability to react to


cases not included in the specification”

javaprogrammering
Correctness
– How do we test (and measure) correctness?

Correctness – “[the software’s] ability to perform


according to specification”

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)

• Assertions include the specification in the


software itself!

• Assertions document why a correct system is


correct (not merely that it is correct)

javaprogrammering
Assertions
• Assertions can be used for checking pre-
conditions, post-conditions, and class invariant

• A pre-condition violation means there’s a bug in


the caller (client)

• A post-condition violation and/or invariant


violation means there’s a bug in the supplier
(probably your own code)

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)

Class invariant – if the “data structure” above is a


class…

javaprogrammering
class MyStack {
Invariant, ex
private char[] cArr; // internal rep
private int i = 0;
.
.
void push(char c) {
cArr[i] = c;
i++;
}
}

The invariant in this example could be expressed: “ i should


always be equal to the size of the stack (i.e. point at one
above at the top of the stack)” ( cArr[i]==(char) 0 ).
– Is the invariant violated anywhere above?
javaprogrammering
Assertions
• Pre-conditions, post-conditions and class
invariant should be possible to check for all
externally accessible methods (at least during
development phase).

• What about assertions in private methods?

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;
}

>javac –source 1.4 *.java


>java –ea MyMainClass

javaprogrammering
Correctness vs. Efficiency?
Assertions take time There is a trade-off
between correctness and efficiency

Should assertions be maintained in the production


phase?

Keep the pre-condition assertions? (in e.g. a class


library)

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!

public float mySqrt(float f) {


assert (f>=0); // is part of specification
// Could we recover from a negative input?
// Should we even try…?
.
.
}

• If input is valid, you have to deliver…


• If it’s not, you can do anything you like!

javaprogrammering
Design by Contract
Applies also at class- and package-level.

Ex: Package-contained software component


• API in the form of an interface
• The interface acts as the specification,
together with assertions (and exceptions) in
implementing class (or, alternatively, together
with a test-suite)

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…

• Internal software-to-software communication vs.


communication to the outside world

javaprogrammering
Robustness
Robustness – “[the software’s] ability to react to
cases not included in the specification”

(Not really measurable…)

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

2. Unchecked exceptions – we can deal with


these too, but usually not during execution

3. Errors – we cannot (or should not) usually deal


with these…

javaprogrammering
Exceptions in Java
Throwable

Error Exception ”checked”

RuntimeException ”unchecked”

(these are all classes – was that a good design choice…?)

javaprogrammering
Exception
• Checked exceptions
- IOException, SQLException, etc
- programmer-defined exceptions (inheriting from Exception)

• Unchecked “runtime” exceptions


- ArrayIndexOutOfBoundsException, NullPointerException etc.

• 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 ();
}
}
}

class MyException extends Exception{}

class MyOtherException extends Exception{}


javaprogrammering
Catching exceptions, ex
try{
dangerousCode(); prints call chain to std.err
}catch (MyException me){
returns message
me.printStackTrace();
}catch (MyOtherException moe){
System.out.println(moe.getMessage());
}catch (Exception e){
System.out.println(e);
} finally {
// always do this, no matter what
}

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;
}

– Use assertions or (unchecked) exceptions?

javaprogrammering
Assertions vs. exceptions
• Assertions should never be checked – they always
mark a broken contract.

• But so do unchecked exceptions…

• Practical consideration:
– Assertions can be easily de-activated.

• Tests may replace both.

• (What about checked exceptions?)

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?

Multiple-tier applications: Different exceptions for different


layers
simple messages
View
general exception with limited info
Presentation

Logic application specific exceptions (+logging)

Integration
DB-related exceptions
DB

javaprogrammering
Re-throwing exceptions
try {

// do some database calls here

} catch (SQLException se) {

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

Corresponding classes for output streams (“…OutputStream”)

javaprogrammering
Character streams
Reader

InputStreamReader

BufferedReader

PipedReader
FileReader

Corresponding classes for writers (“…Writer”)

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

( This is an example of the Decorator design pattern! )

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:

static InputStream in; // typically keyboard


static PrintStream out; // typically console
static PrintStream err; // typically console

• (PrintStream inherits from FilterOutputStream and


contains overloaded methods for printing different types)

javaprogrammering
Saving objects
• Use serialization to save the current state of an object.

• Implement interface Serializable (no methods)

• Make sure every attribute is in fact serializable…

• (Most standard classes implement Serializable)

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();
}

• NotSerializableException – If we try to save an


object which does not implement Serializable

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.:

private transient String lösenOrd =


”krYpt_67RyteR”;

private transient Connection conn;

private transient Thread myThread;

javaprogrammering
Exercise, bank 3
• Save the bank system on disk
– (when shutting down, save current state first)

• Read the bank system from disk


– (when starting up, check if there’s a bank available for loading)

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.

You might also like