Sie sind auf Seite 1von 80

Software Design But first:

Models, Tools & Processes Introduction to Java (with BlueJ)

Three lectures adapted from


Alan Blackwell
Objects First with Java:
Cambridge University A Practical Introduction using BlueJ
Computer Science Tripos Part 1a
© David J. Barnes, Michael Kölling

First lecture Second lecture


“ using BlueJ “ constructors
“ objects “ assignment statements
“ classes “ conditional statements
“ methods “ collections
“ parameters “ loops
“ fields “ iterators
Third lecture Lectures 4-12
“ arrays “ Software engineering
“ inheritance “ Unified modeling language
“ polymorphism “ Object-oriented design
“ data types “ Programming style
“ equality and identity “ Development processes
“ User-centred design
“ Testing and debugging
“ Configuration and releases
“ Prototyping
“ Agile development

BlueJ BlueJ
book book
“ (Many first
editions still
around
Cambridge
from 2004)
BlueJ Demo Fundamental concepts
“ object
“ class
“ method
“ parameter
“ data type

Objects and classes Methods and parameters


“ objects “ objects have operations which can be
“ represent ‘things’ from the real world, or from invoked (Java calls them methods)
some problem domain (example: “the red car “ methods may have parameters to pass
down there in the car park”)
additional information needed to execute
“ classes “ as with ML functions
“ represent all objects of a kind (example: “car”)
Other observations State
“ many instances can be created from a single
class
“ an object has attributes: values stored in
fields.
“ the class defines what fields an object has,
but each object stores its own set of values
(the state of the object)

Two circle objects Source code


“ Each class has source code (Java code)
associated with it that defines its details
(fields and methods).
Return values
“ Methods may return a result via a “return
value”.
“ another respect in which methods are like ML
functions
“ in fact, many people may accidentally call Java
methods ‘functions’
Understanding class definitions
“ Some ancestors of Java:
“ C and Pascal have ‘functions’ Looking inside classes
“ Smalltalk has ‘methods’
“ C++ has ‘member functions’

1.0

Main concepts to be covered BlueJ example: Ticket machine


“ fields Use BlueJ to explore the behavior of simple
“ constructors application:
“ methods “ See the naive-ticket-machine project.

“ parameters “ Machines supply tickets of a fixed price.

“ assignment statements
“ How is that price determined?

“ conditional statements
“ How is ‘money’ entered into a machine?
“ How does a machine keep track of the money
that is entered?
Ticket machine – internal view Basic class structure
“ Interacting with an object gives us clues
about its behavior. outer wrapper
public class TicketMachine
of TicketMachine
“ Looking inside allows us to determine how {
Inner part of the class omitted.
that behavior is provided or implemented. }
“ All Java classes have a similar-looking
internal view.
public class ClassName
{
Fields contents of a
Constructors
generic class
Methods
}

Fields public class TicketMachine


{
Constructors
“ Fields store values for private int price; “ Constructors initialize object state.
private int balance;
an object. private int total; “ They have the same name as their class.
“ also called “instance
“ They store initial values into the fields.
variables”. Constructor and
methods omitted. “ They often receive external parameter
“ Use Inspect in BlueJ to
} values for this.
view an object’s fields.
“ Fields define the state
of an object. public TicketMachine(int ticketCost)
type {
visibility modifier variable name price = ticketCost;
balance = 0;
total = 0;
private int price; }
Passing data via parameters Assignment
“ Values are stored into fields (and other
variables) via assignment statements:
“ variable = expression;
“ price = ticketCost;

“ A variable stores a single value, so any


previous value is lost.

Accessor methods Accessor methods


“ Methods implement the behavior of objects. return type method name
“ Accessors provide information about an visibility modifier
object, getting access to its state
“ Methods have a structure consisting of a public int getPrice()
header and a body. {
return price; parameter list
} (empty)
“ The header defines the method’s signature.
public int getPrice()
return statement gets value based on object state

“ The body encloses the method’s statements. start and end of method body (block)
Mutator methods Mutator methods
“ Have a similar method structure: header and
return type (void)
body.
method name parameter
“ But these are used to mutate (i.e., change) visibility modifier
an object’s state.
“ Achieved through changing the value of one public void insertMoney(int amount)
or more fields. {
“ Typically contain assignment statements. balance += amount;
}
“ Typically receive parameters.

assignment statement
field being changed

Printing from methods Improving basic ticket machines


public void printTicket() “ Their behavior is inadequate in several ways:
{ “ No checks on the amounts entered.
// Simulate the printing of a ticket.
System.out.println("##################");
“ No refunds.
System.out.println("# The BlueJ Line"); “ No checks for a sensible initialization.
System.out.println("# Ticket");
System.out.println("# " + price + " cents."); “ How can we do better?
System.out.println("##################"); “ We need more sophisticated behavior.
System.out.println();

// Update the total collected with the balance.


total += balance;
// Clear the balance.
balance = 0;
}
Making choices Making choices
boolean condition to be tested - gives a true or false result
public void insertMoney(int amount) ‘if’ keyword
{ actions if condition is true
if(amount > 0) {
balance += amount; if (perform some test) {
} Do the statements here if the
else { test gave a true result
System.out.println( }
"Use a positive amount: ” else {
+ amount Do the statements here if the
); test gave a false result
} }
}
‘else’ keyword
actions if condition is false

Local variables Local variables


“ Fields are one sort of variable.
“ They store values through the life of an object. A local variable
“ They define the state of the object. public int refundBalance()
{
“ They are accessible from all methods of the class.
int amountToRefund;
“ Methods can include shorter-lived variables. amountToRefund = balance;
“ They exist only as long as the method is being No visibility balance = 0;
executed. modifier return amountToRefund;
“ They are only accessible from within the method. }
“ They are not considered part of the object state.
A digital clock

Object interaction
Creating cooperating objects

1.0

Abstraction and modularization Modularizing the clock display


“ Abstraction is the ability to ignore details of
parts to focus attention on a higher level of a
problem.
“ Modularization is the process of dividing a
One four-digit display?
whole into well-defined parts, which can be
built and examined separately, and which
interact in well-defined ways.
Or two two-digit
“ Much more on this later in the course … displays?
Implementation - NumberDisplay Implementation - ClockDisplay

public class NumberDisplay public class ClockDisplay


{ {
private int limit; private NumberDisplay hours;
private int value; private NumberDisplay minutes;

Constructor and Constructor and


methods omitted. methods omitted.

} }

Object diagram Class diagram


Primitive types vs. object types Primitive types vs. object types

SomeObject a; SomeObject b;
SomeObject obj;
“object” type

b = a;
int i;
int a; int b;
32 “primitive” type 32 32

Source code: NumberDisplay Source code: NumberDisplay

public NumberDisplay(int rollOverLimit) public String getDisplayValue()


{ {
limit = rollOverLimit; if(value < 10)
value = 0; return "0" + value;
} else
return "" + value;
public void increment() }
{
value = (value + 1) % limit;
}
Objects creating objects Method calling
public class ClockDisplay
{ public void timeTick()
private NumberDisplay hours; {
private NumberDisplay minutes; minutes.increment();
private String displayString; if(minutes.getValue() == 0) {
// it just rolled over!
public ClockDisplay() hours.increment();
{ }
hours = new NumberDisplay(24); updateDisplay();
minutes = new NumberDisplay(60); }
updateDisplay();
}
}

Internal method ClockDisplay object diagram

/**
* Update the internal string that
* represents the display.
*/

private void updateDisplay()


{
displayString =
hours.getDisplayValue() + ":" +
minutes.getDisplayValue();
}
Passing state between objects Method calls
“ internal method calls
“ Call using:
in class NumberDisplay:
updateDisplay();
public NumberDisplay(int rollOverLimit);
“ Define using:
private void updateDisplay()
formal parameter
“ external method calls – call using:
in class ClockDisplay:
minutes.increment();
hours = new NumberDisplay(24);

object . methodName ( parameter-list )


actual parameter

Review Review
“ Class bodies contain fields, constructors and “ Local variables are used for short-lived
methods. temporary storage.
“ Fields store values that determine an object’s “ Objects can make decisions via conditional
state. (if) statements.
“ Constructors initialize objects. “ A true or false test allows one of two
“ Methods implement the behavior of objects alternative courses of actions to be taken.
“ Fields, parameters and local variables are all “ Objects can create other objects
variables. “ They can interact via method calls
“ Fields persist for the lifetime of an object. “ An object can call its own internal methods
“ Parameters are used to receive values into a
constructor or method.
Concepts
“ abstraction “ primitive types
“ modularization “ object types
“ classes define types “ object creation
“ class diagram “ internal/external Grouping objects
“ object diagram method call
“ object references
Collections and iterators

1.0

Main concepts to be covered The requirement to group objects


“ Collections “ Many applications involve collections of
“ Loops objects:
“ Iterators
“ Personal organizers.
“ Library catalogs.
“ Arrays
“ Student-record system.
“ The number of items to be stored varies.
“ Items get added.
“ Items get deleted.
Example: a personal notebook Class libraries
“ Notes may be stored. “ Collections of useful classes.
“ Individual notes can be viewed. “ We don’t have to write everything from
scratch.
“ There is no limit to the number of notes.
“ Java calls its libraries ‘packages’.
“ It will tell how many notes are stored.
“ Grouping objects is a recurring requirement.
“ BlueJ example notebook1 project. “ The java.util package contains classes for
doing this.

import java.util.ArrayList;

/** Object structures with collections


* ... Define which
*/ package the class
will come from
public class Notebook
{
// Storage for any number of notes.
private ArrayList notes;

/** Declare variable


* Initialise the notebook. of type ArrayList
*/
public Notebook()
{
notes = new ArrayList();
}
Create an instance
... of ArrayList class
}
Adding a third note Features of the collection
“ It increases its capacity as necessary.
“ It keeps a private count (size() accessor).
“ It keeps the objects in order.
“ Details of how all this is done are hidden.
“ Does that matter? Does not knowing how prevent
us from using it?
“ The size operation can be ‘delegated’ without
knowing how it is achieved, so long as the
signature is known

Using the collection Index numbering


public class Notebook
{
private ArrayList notes;
...

public void storeNote(String note)


{
notes.add(note); Adding a new note
}

public int numberOfNotes()


{
return notes.size(); Returning the number of notes
} (delegation).

...
}
Retrieving an object Removal may affect numbering
Index validity checks

public void showNote(int noteNumber)


{
if(noteNumber < 0) {
// This is not a valid note number.
}
else if(noteNumber < numberOfNotes()) {
System.out.println(notes.get(noteNumber));
}
else {
// This is not a valid note number.
}
}

Retrieve and print the note

Review Review
“ Collections allow an arbitrary number of “ Items may be added and removed.
objects to be stored. “ Each item has an index.
“ Class libraries usually contain tried-and- “ Index values may change if items are
tested collection classes. removed (or further items added).
“ Java’s class libraries are called packages. “ The main ArrayList methods are add,
“ We have used the ArrayList class from get, remove and size.
the java.util package.
Iteration ‘While’ loop – pseudo code
“ We often want to perform some actions an General form of a while-loop
Boolean test
arbitrary number of times.
while keyword
“ E.g., print all the notes in the notebook. How many
are there?
while ( loop condition ) {
“ Most programming languages include loop loop body – code to be
statements to make this possible. repeated
“ Java has three sorts of loop statement.
}
“ We will focus on its while loop. Statements to be repeated
Example to print every note
while(there is at least one more note to be printed) {
show the next note
}

A Java example Iterating over a collection


/**
* List all notes in the notebook. java.util.Iterator Returns an Iterator object
*/ Iterator it = myCollection.iterator();
while(it.hasNext()) {
public void listNotes() call it.next() to get the next object
do something with that object
{ }
int index = 0;
while(index < notes.size()) {
System.out.println(notes.get(index));
public void listNotes()
index++; {
} Iterator it = notes.iterator();
} while(it.hasNext()) {
Increment by one System.out.println(it.next());
}
}
Review Fixed-size collections
“ Loop statements allow a block of statements “ Sometimes the maximum collection size can
to be repeated. be pre-determined.
“ A Java while loop allows the repetition to be “ Programming languages usually offer a
controlled by a boolean expression. special fixed-size collection type: an array.
“ Collection classes have special Iterator “ Java arrays can store objects or primitive-
objects that simplify iteration over the whole type values.
collection. “ Arrays use a special syntax.

Creating an array object An array in memory


Array variable declaration
public class LogAnalyzer
{
private int[] hourCounts;
private LogfileReader reader;
Array object creation
public LogAnalyzer()
{
hourCounts = new int[24];
reader = new LogfileReader();
}
...
}
Using an array The ‘for’ loop
“ Unlike collections “ Similar to a while-loop.
“ Removing items doesn’t change numbering “ Often used to iterate a fixed number of times.
“ But size doesn’t change dynamically either “ Often used to iterate over an array.
“ Square-bracket notation is used to access an
array element: Can be number,
“ hourCounts[...] variable or expression
“ Elements are used like ordinary variables.
“ On the left of an assignment:
“ hourCounts[hour] = ...;
“ In an expression:
“ adjusted = hourCounts[hour] – 3;
“ hourCounts[hour]++;

‘For’ loop - pseudo-code A Java example


General form of a for-loop
for-loop version
for(initialization; condition; post-body action) {
statements to be repeated for(int hour = 0; hour < hourCounts.length; hour++) {
} System.out.println(hour + ": " + hourCounts[hour]);
}

Equivalent in while-loop form while-loop version


initialization; int hour = 0;
while(condition) { while(hour < hourCounts.length) {
statements to be repeated System.out.println(hour + ": " + hourCounts[hour]);
post-body action hour++;
} }
Review The Java class library
“ Arrays are appropriate where a fixed-size “ Thousands of classes
collection is required. “ Tens of thousands of methods
“ Arrays use special syntax. “ Many useful classes that make life much
“ For-loops offer an alternative to while-loops easier
when the number of repetitions is known. “ A competent Java programmer must be able
“ For-loops are often used to iterate over to work with the libraries.
arrays.

Reading class documentation Interface vs implementation


“ Documentation of the Java libraries in HTML The documentation includes:
format; “ the name of the class;
“ Readable in a web browser “ a general description of the class;
“ Class API: Application Programmers’ “ a list of constructors and methods
Interface “ return values and parameters for constructors
“ Interface description for all library classes and methods
“ a description of the purpose of each
constructor and method

the interface of the class


Interface vs implementation
The documentation does not include

“ private fields (most fields are private)


“ private methods Inheritance
“ the bodies (source code) for each method

the implementation of the class

1.0

Inheritance hierarchies Simple example


Using inheritance Inheritance in Java no change

“ define one superclass : Vehicle public class Vehicle


“ define subclasses for Car and Bicycle {
... different here
“ the superclass defines common attributes }
“ the subclasses inherit the superclass
attributes that they will have in common public class Bicycle extends Vehicle
“ the subclasses add their own attributes {
...
}
“ In Java, attributes are defined using fields,
and subclasses as an ‘extends’ relationship public class Car extends Vehicle
between classes. {
...
}

Superclass Subclasses

public class Car extends Vehicle


public class Vehicle {
{ private int engineSize;
private String colour; }
private int kerbWeight;

// constructor and methods public class Bicycle extends Vehicle


// omitted {
} private int numberGears;
private boolean stabilisers;
}
Inheritance and constructors Inheritance and constructors
public class Car extends Vehicle
public class Vehicle {
{ private int engineSize;
private String colour;
private int kerbWeight; /**
* Constructor for objects of class Car
/** */
* Initialise the fields of Vehicle. public Car(String paint,
*/ int weight, int engine)
public Vehicle(String paint, int weight) {
{ super(paint, weight);
kerbWeight = weight; engineSize = engine;
colour = paint; }
} }
}
calls superclass constructor

Superclass constructor call Subclasses and subtyping


“ Subclass constructors must always contain a “ Classes define types.
'super' call. “ Subclasses define subtypes.
“ The ‘super’ call must be the first statement in “ Objects of subclasses can be used where
the subclass constructor. objects of supertypes are required.
“ If none is written, the compiler inserts one (This is called substitution)
(without parameters)
“ Be careful: this will work only if the superclass has subtype
“ Compare: statement
defined a suitable constructor without parameters
“ A bicycle is a type of vehicle about
“ I’m going to work by vehicle supertype
“ I’m going to work by bicycle
“ I’m going to work by car
substitutions
Subtyping and assignment The Object class
all classes inherit
from Object
subclass objects
may be assigned to
superclass
variables

Vehicle v1 = new Vehicle();


Vehicle v2 = new Car();
Vehicle v3 = new Bicycle();

Polymorphism Casting
“ Java collection classes are polymorphic “ Allowed to assign subtype to supertype.
“ They can operate on many different types “ Not allowed to assign supertype to subtype!

String s1 = myList.get(1); error!


“ The elements stored in a collection are “ Why?
actually defined to be of type Object.
“ My vehicle is rolling Î my bicycle is rolling OK
“ Parameters and return values of the collection
“ I pedal my bicycle Î I pedal my vehicle
class’s mutator and accessor methods are also
defined as type Object: Not OK
“ Casting makes it seem OK:
public void add(Object element)
String s1 = (String) myList.get(1);
public Object get(int index)
(but must be sure this really will be a String!)
The do … while loop
while keyword
while loop Boolean test

while(loop condition) {
loop body Statements to be repeated
A few more Java features }

do … while loop
do keyword

Body executes at least once


do {
loop body
} while (loop condition)

while keyword Boolean test after loop


1.0

The switch statement Example of switch


switch (expression) char response = reader.getChar();
{ Value to switch on
case value: switch (response)
statements; {
Any number of case labels
break; case 'y':
case value: answer = "Loves me";
statements; Stops execution break;
break; “falling through” case 'n':
case value: to next case
answer = "Loves me not";
statements; break;
break; default:
default: Optional: guarantees answer = "Confusion";
statements; something happens
break;
break; }
}
switch versus if … else Primitive data types (1)
“ boolean
char response = reader.getChar(); “ Only two values: true or false
“ int
if (response == 'y') {
answer = "Loves me"; “ 32 bit integer (literals: 1294123, -88123)
} “ byte
else if (response == 'n') { “ 8-bit integer (literals: 24, -2)
answer = "Loves me not"; “ short
}
“ 16 bit integer (literals: 5409, -2004)
else {
answer = "Confusion"; “ long
} “ 64 bit integer (literals: 4232663531, 55L)

Primitive data types (2) Operators


“ char “ Assignment (all primitive and object types)
“ Unicode character (16 bit) “ =
(literals: 'm', '\u00F6') “ Arithmetic (numeric Î numeric)
“ float “ + - / * %
“ Single precision floating point “ Increment (numeric Î numeric)
(literals: 43.889F) “ += -= ++ --
“ double “ Relational (most types Î boolean)
“ == != > < <= >=
“ Double precision floating point
(literals: 45.63, 2.4e5) “ Boolean (boolean Î boolean)
“ && || ^ !
Strings: a common trap Identity vs equality 1
if(input == "bye") {
... Other (non-String) objects:
tests identity: is this the
} same instance of string?
:Person :Person

“Fred” “Jill”
if(input.equals("bye")) {
...
} tests equality: does this string
have the same letters? person1 person2

“ Strings should (almost) always be compared


using.equals person1 == person2 ?

Identity vs equality 2 Identity vs equality 3

Other (non-String) objects: Other (non-String) objects:

:Person :Person :Person :Person

“Fred” “Fred” “Fred” “Fred”

person1 person2 person1 person2

person1 == person2 ? person1 == person2 ?


Identity vs equality (Strings) Identity vs equality (Strings)
String input = reader.getInput(); String input = reader.getInput();
if(input == "bye") { if(input.equals("bye")) {
... ...
} “==” tests identity } “equals” tests equality

:String :String :String :String

"bye" == "bye" ? "bye" equals "bye" ?

input
Æ (may be) false!
input
Æ true!

How hard can it be?


“ State what the system should do
“ {D1, D2, D3 …}

Software Design “ State what it shouldn’t do


“ {U1, U2, U3 …}
Models, Tools & Processes
“ Systematically add features
“ that can be proven to implement Dn
Alan Blackwell “ while not implementing Un

Cambridge University
Computer Science Tripos Part 1a
How hard can it be … … to define this system?
“ The United Kingdom Passport Agency
“ http://www.parliament.the-stationery-office.co.uk/
pa/cm199900/cmselect/cmpubacc/65/6509.htm
“ 1997 contract for new computer system born in issue
“ aimed to improve issuing efficiency, on tight project timetable UK passport
“ project delays meant throughput not thoroughly tested
“ first live office failed the throughput criterion to continue roll-out
“ second office went live, roll out halted, but no contingency plan
return to record record
“ rising backlog in early 1999, alongside increasing demand
leave UK UK exit entry
“ passport processing times reached 50 days in July 1999
“ widespread publicity, anxiety and panic for travelling public
“ telephone service overloaded, public had to queue at UKPA offices
“ only emergency measures eventually reduced backlog
dies cancel
“ So how hard can it be to issue a passport?
“ … let’s try some simple definition

How hard can it be … Why is the world complicated?


“ Bureaucratic systems are complex because
managers (and people) always mess up
“ Passports
“ Ambulance systems (more in part 1B)
“ University financial systems (later in this course)
“ What about physical systems, which don’t
… to define a simple rely on people to work?
bureaucracy? “ Start with known characteristics of physical
device.
“ Assemble behaviours to achieve function
“ This is how engineering products (bridges and
aircraft) are designed.
How hard can it be … … to define a physical system?

Design and uncertainty What is the problem?


“ A good programmer should be able to: “ The problem is not that we don’t understand
“ Create a system that behaves as expected. the computer.
“ Behaves that way reliably. “ The problem is that we don’t understand the
“ But a good designer must also: problem!
“ Take account of the unexpected. “ Does computer science offer any answers?
“ A well-designed software system is not the “ The good news:
same as a well-designed algorithm. “ We’ve been working on it since 1968
“ If the requirements change or vary, “ The bad news:
you might replace the algorithm,
“ There is still no “silver bullet”!
“ But it’s seldom possible to replace (from great IBM pioneer Fred Brooks)
a whole system.
Pioneers – Bavarian Alps, 1968
“ 1954: complexity of
SAGE air-defence
project was under-
estimated by 6000
person-years …
Introduction “ … at a time when
there were only
about 1000
programmers
A design process based on knowledge in the whole world!
“ … “Software Crisis!”

“ 1968: First meeting on “Software Engineering”


convened in Garmisch-Partenkirchen.

Design and ignorance Learning by building models


“ Some say software engineering is the part “ The software design process involves gaining
that is too hard for computer scientists. knowledge about a problem, and about its
“ But the real change was understanding the technical solution.
importance of what you don’t know “ We describe both the problem and the
“ dealing with uncertainty, lack of knowledge … solution in a series of design models.
“ … but trying to be systematically ignorant! “ Testing, manipulating and transforming those
“ Design is a process, not a set of known facts models helps us gather more knowledge.
“ process of learning about a problem “ One of the most detailed models is written in
“ process of describing a solution a programming language.
“ at first with many gaps … “ Getting a working program is almost a side-effect
“ eventually in sufficient detail to build the solution of describing it!
Unified Modeling Language Outline for the rest of the course
“ Use Case diagrams - interactions with / interfaces “ Roughly follows stages of the (UML-related)
to the system. Rational Unified Process
“ Class diagrams - type structure of the system. “ Inception
“ Collaboration diagrams - interaction between “ structured description of what system must do
instances “ Elaboration
“ Sequence diagrams - temporal structure of “ defining classes, data and system structure
interaction “ Construction
“ Activity diagrams - ordering of operations “ object interaction, behaviour and state
“ Statechart diagrams - behaviour of individual “ Transition
objects “ testing and optimisation
“ Component and Deployment diagrams - system “ Plus allowance for iteration
organisation
“ at every stage, and through all stages

Older terminology: the “waterfall” Modern alternative: the “spiral”


Evaluate alternatives
and resolve risks
Requirements

Prototype
Specification 2

Implementation
& unit testing
Initial plan
Integration & Prototype
system testing 1
Operations &
maintenance Requirements
Development Code
plan Test
Integrate
Implement Develop and verify
Plan next phases next level product
The Design Process vs. The Design Books
Inception “ Code Complete: A practical handbook of software construction
Usage Model Use Case Diagrams “ Steve McConnell, Microsoft Press 2004 (2nd edition)
“ UML Distilled: A brief guide to the standard object modeling language
Structure Model Class Diagrams “ Martin Fowler, Addison-Wesley 2003 (3rd edition)
“ Further:
Elaboration Behaviour Models Statechart Diagrams
“ Software Pioneers, Broy & Denert
Activity Diagrams
“ Software Engineering, Roger Pressman
Interaction Models “ The Mythical Man-Month, Fred Brooks
Sequence Diagrams
“ The Design of Everyday Things, Donald Norman
Collaboration Diagrams
Construction “ Contextual Design, Hugh Beyer & Karen Holtzblatt
“ The Sciences of the Artificial, Herbert Simon
Implementation
Component Diagrams
“ Educating the Reflective Practitioner, Donald Schon
Models
Deployment Diagrams “ Designing Engineers, Louis Bucciarelli

Transition

Exam questions
“ This syllabus appeared under this name for
the first time in 2006 (without Java element):
“ Software Design 2006, Paper 2, Q7
“ But syllabus was previously introduced as:
“ Software Engineering II 2005, Paper 2, Q8
Inception phase
“ Some components had previously been
taught elsewhere in the Tripos: structured description of system usage
“ Programming in Java 2004, Paper 1, Q10 and function
“ Software Engineering and Design 2003 Paper 10,
Q12 and 2004 Paper 11, Q11
“ Additional Topics 2000, Paper 7, Q13
Pioneers – Tom DeMarco
“ Structured Analysis
“ 1978, Yourdon Inc
“ Defined the critical technical role of the
system analyst
“ Analyst acts as a middleman between users and
How can you capture requirements?
(technical) developers
“ Analyst’s job is to construct a functional
specification
“ data dictionary, data flow, system partitioning

Analysing requirements Interaction design bugs


“ Analysis usually involves (re)negotiation of
requirements between client and designer.
“ Once considered “requirements capture”.
“ Now more often “user-centred design”.
“ An “interaction designer” often replaces (or
works alongside) traditional systems analysts.
“ Professional interaction design typically combines
research methods from social sciences with visual
or typographic design skills (and perhaps CS).
Interaction design bugs Interaction design bugs

From Interface Hall of Shame

The psychological approach The anthropological approach


“ Anticipate what will happen when someone “ Carry out fieldwork:
tries to use the system. “ Interview the users.
“ Design a “conceptual model” that will help them “ Understand the context they work in.
(and you) develop shared understanding. “ Observe the nature of their tasks.
“ The gulf of execution: “ Discover things by observation that they might not
“ System users know what they want to achieve, have told you in a design brief.
but can’t work out how to do it. “ Collaborate with users to agree:
“ The gulf of evaluation: “ What problem ought to be solved.
“ Systems fail to give suitable feedback on what just “ How to solve it (perhaps by reviewing sketches of
happened, so users never learn what to do. proposed screens etc.).
“ See Norman: Design of Everyday Things.
“ Far more detail to come in Part II HCI course
Ethnographic field studies Design ‘ethnography’
“ Understand real detail of user activity, not just “ Study division of labour and its coordination
official story, theories or rationalisations. “ Plans and procedures
“ Researchers work in the field: “ When do they succeed and fail?
“ Observing context of people’s lives “ Where paperwork meets computer work
“ Ideally participating in their activities “ Local knowledge and everyday skills
“ Academic ethnography tends to: “ Spatial and temporal organisation
“ Observe subjects in a range of contexts. “ Organisational memory
“ Observe over a substantial period of time. “ How do people learn to do their work?
“ Make full record of both activities and artefacts. “ Do formal/official methods match reality?
“ Use transcripts of video/audio recordings. “ See Beyer & Holtzblatt, Contextual Design

Interviews User Personas


“ Field work usually includes interviews “ This is a way to ‘distil’ information about users
“ Additional to requirements meetings with client “ from field work, interviews, user studies etc
“ into a form that is more useful to design teams.
“ Often conducted in the place of work during
‘contextual enquiry’ (as in Beyer & Holtzblatt) “ Write fictional portraits of individuals
“ emphasis on user tasks, not technical issues
representing various kinds of user
“ give them names, jobs, and personal history
“ Plan questions in advance
“ often include photographs (from libraries ,actors)
“ ensure all important aspects covered
“ Help software engineers to remember that
“ May be based on theoretical framework, e.g. customers are not like them …
“ activities, methods and connections “ … or their friends …
“ measures, exceptions and domain knowledge “ … or anyone they’ve ever met!
Designing system-use scenarios UML Use Case diagram
“ Aim is to describe the human activity that the
system has to carry out or support.
“ Known as use cases in UML
“ Use cases help the designer to discover and
record interactions between software objects.
“ Can be refined as a group activity, based on
personas, or in discussion with clients.
“ May include mock-ups of screen designs, or
physical prototypes.
“ Organised and grouped in use case diagrams

UML Use Case diagram Objects in a scenario


“ Actors “ The nouns in a description refer to ‘things’.
“ play system role “ A source of classes and objects.
“ may not be people
“ Use case
“ The verbs refer to actions.
“ like a scenario “ A source of interactions between objects.
“ Relationships “ Actions describe object behavior, and hence
“ include required methods.
“ extend
“ generalisation
Example of problem description Nouns
The cinema booking system should store seat bookings for The cinema booking system should store seat bookings for
multiple theatres. multiple theatres.

Each theatre has seats arranged in rows. Each theatre has seats arranged in rows.

Customers can reserve seats and are given a row number Customers can reserve seats and are given a row number
and seat number. and seat number.

They may request bookings of several adjoining seats. They may request bookings of several adjoining seats.

Each booking is for a particular show (i.e., the screening of Each booking is for a particular show (i.e., the screening of
a given movie at a certain time). a given movie at a certain time).

Shows are at an assigned date and time, and scheduled in a Shows are at an assigned date and time, and scheduled in a
theatre where they are screened. theatre where they are screened.

The system stores the customers’ telephone number. The system stores the customers’ telephone number.

Verbs Extracted nouns & verbs


The cinema booking system should store seat bookings for
multiple theatres.
Cinema booking system Theatre Movie
Stores (seat bookings) Has (seats)
Each theatre has seats arranged in rows.
Stores (telephone number)

Customers can reserve seats and are given a row number


and seat number. Customer Time Date
Reserves (seats)
They may request bookings of several adjoining seats. Is given (row number, seat number)
Requests (seat booking) Seat booking
Each booking is for a particular show (i.e., the screening of
a given movie at a certain time). Show Seat Seat number
Is scheduled (in theatre)
Shows are at an assigned date and time, and scheduled in a
theatre where they are screened. Telephone number Row Row number

The system stores the customers’ telephone number.


Scenario structure: CRC cards Typical CRC card
“ First described by Kent Beck and Ward
Cunningham. Class name Collaborators
“ Later innovators of “agile” programming
Responsibilities
(more on this later in course)
“ Use simple index cards, with each cards
recording:
“ A class name.
“ The class’s responsibilities.
“ The class’s collaborators.

Partial example Refinement of usage model


“ Scenarios allow you to check that the
problem description is clear and complete.
CinemaBookingSystem Collaborators
Can find movies by Movie “ Analysis leads gradually into design.
title and day. “ Talking through scenarios & class responsibilities
Stores collection of Collection leads to elaborated models.
movies. “ Spotting errors or omissions here will save
Retrieves and displays
considerable wasted effort later!
movie details.
... “ Sufficient time should be taken over the analysis.
“ CRC was designed to allow (in principle) review
and discussion with analysts and/or clients.
Pioneers – Peter Chen
“ Entity-Relationship Modeling
“ 1976, Massachusetts Institute of Technology
“ User-oriented response to Codd’s relational
database model
Elaboration “ Define attributes and values
“ Relations as associations between things
“ Things play a role in the relation.
defining classes, data and system
structure “ E-R Diagrams showed entity (box), relation
(diamond), role (links).
“ Object-oriented Class Diagrams show class
(box) and association (links)

Review of objects and classes Typical classes and associations


“ objects Movie
“ represent ‘things’ in some problem domain
(example: “the red car down in the car park”) Time Date
“ classes
“ represent all objects of a kind (example: “car”) Seat booking Theatre

“ operations
“ actions invoked on objects (Java “methods”) Customer
Seat Row
“ instance
Telephone number
“ can create many instances from a single class
“ state NB: one class, Number
“ all the attributes (field values) of an instance two uses
UML Class
diagram UML Class diagram
“ Attributes
“ type and visibility
“ Operations
“ signature and visibility
“ Relationships
“ association
“ with multiplicity
“ potentially aggregation
“ generalisation

Association and aggregation Implementing association in Java


The cinema booking system should store seat bookings for public class Car {
multiple theatres. Car private String colour;
private Carpark park;
Each theatre has seats arranged in rows. colour
* ...
Customers can reserve seats and are given a row number
and seat number.
park_me (Carpark where)
They may request bookings of several adjoining seats. 0..1 {
park = where;
Each booking is for a particular show (i.e., the screening of Carpark }
a given movie at a certain time). address
Shows are at an assigned date and time, and scheduled in a
theatre where they are screened.

The system stores the customers’ telephone number.


Multiple association in Java Implementing multiple associations
public class Carpark { Summary from 3 Java lectures:
Car private String address;
“ Most applications involve collections of
colour private ArrayList my_cars;
objects
* ... “ java.util package contains classes for this

add_car (Car new_car) “ The number of items to be stored varies


0..1 { “ Items can be added and deleted
my_cars.add(new_car); “ Collection increases capacity as necessary
Carpark
}
address “ Count of items obtained with size()
“ Items kept in order, accessed with iterator
“ Details of how all this is done are hidden.

Class design from CRC cards Refining class interfaces


“ Scenario analysis helps to clarify application “ Replay the scenarios in terms of method
structure. calls, parameters and return values.
“ Each card maps to a class. “ Note down the resulting method signatures.
“ Collaborations reveal class cooperation/object “ Create outline classes with public-method
interaction.
stubs.
“ Responsibilities reveal public methods.
“ Careful design is a key to successful
“ And sometimes fields; e.g. “Stores collection ...”
implementation.
Dividing up a design model Pioneers – David Parnas
“ Abstraction “ Information Hiding
“ Ignore details in order to focus on higher level “ 1972, Carnegie Mellon University
problems (e.g. aggregation, inheritance). “ How do you decide the points at which a
“ If classes correspond well to types in domain they program should be split into pieces?
will be easy to understand, maintain and reuse.
“ Are small modules better?
“ Modularization “ Are big modules better?
“ Divide model into parts that can be built and “ What is the optimum boundary size?
tested separately, interacting in well-defined ways.
“ Allows different teams to work on each part
“ Parnas proposed the best criterion for
modularization:
“ Clearly defined interfaces mean teams can work
independently & concurrently, with increased “ Aim to hide design decisions within the module.
chance of successful integration.

Information hiding in OO models Cohesion in OO models


“ Data belonging to one object is hidden from “ Aim for high cohesion:
other objects. “ Each component achieves only “one thing”
“ Know what an object can do, not how it does it.
“ Method (functional) cohesion
“ Increases independence, essential for large
systems and later maintenance “ Method only performs out one operation
“ Use Java visibility to hide implementation “ Groups things that must be done together
“ Only methods intended for interface to other “ Class (type) cohesion
classes should be public. “ Easy to understand & reuse as a domain concept
“ Fields should be private – accessible only within
the same class. “ Causes of low, poor, cohesion
“ Accessor methods provide information about “ Sequence of operations with no necessary relation
object state, but don’t change it. “ Unrelated operations selected by control flags
“ Mutator methods change an object’s state. “ No relation at all – just a bag of code
UML Collaboration diagram

Construction

object interaction, behaviour and state

UML Collaboration
diagram UML Sequence diagram
“ Objects
“ class instances
“ can be transient
“ Links
“ from associations
“ Messages
“ travel along links
“ numbered to show
sequence
UML Sequence diagram Loose coupling
“ Interaction again “ Coupling: links between parts of a program.
“ same content as
collaboration “ If two classes depend closely on details of
“ emphasises time each other, they are tightly coupled.
dimension
“ We aim for loose coupling.
“ Object lifeline
“ keep parts of design clear & independent
“ objects across page
“ time down page
“ may take several design iterations
“ Shows focus of control “ Loose coupling makes it possible to:
“ achieve reusability, modifiability
“ understand one class without reading others;
“ change one class without affecting others.
“ Thus improves maintainability.

Responsibility-driven design Interfaces as specifications


“ Which class should I add a new method to? “ Define method signatures for classes to
“ Each class should be responsible for manipulating interact
its own data. “ Include parameter and return types.
“ The class that owns the data should be “ Strong separation of required functionality from
responsible for processing it. the code that implements it (information hiding).
“ Leads to low coupling & “client-server “ Clients interact independently of the
contracts” implementation.
“ Consider every object as a server “ But clients can choose from alternative
“ Improves reliability, partitioning, graceful implementations.
degradation
Interfaces in Java Alternative implementations
“ Provide specification without implementation.
“ Fully abstract – define interface only
“ Implementing classes don’t inherit code
“ Support not only polymorphism, but
multiple inheritance
“ implementing classes are still subtypes of the
interface type, but allowed more than one “parent”.

public class ArrayList implements List

public class LinkedList implements List

Note difference from ‘extends’


keyword used for sub-classing

Causes of error situations Defensive programming


“ Incorrect implementation. “ Client-server interaction.
“ Does not meet the specification. “ Should a server assume that clients are
“ Inappropriate object request. well-behaved?
“ E.g., invalid index. “ Or should it assume that clients are
potentially hostile?
“ Inconsistent or inappropriate object state.
“ Significant differences in implementation
“ E.g. arising through class extension.
required.
“ Not always programmer error
“ Issues to be addressed
“ Errors often arise from the environment
(incorrect URL entered, network interruption). “ How much checking by a server on method calls?
“ File processing often error-prone “ How to report errors?
(missing files, lack of appropriate permissions). “ How can a client anticipate failure?
“ How should a client deal with failure?
Argument values Example of diagnostic return
“ Arguments represent a major ‘vulnerability’
for a server object. public boolean removeDetails(String key)
{
“ Constructor arguments initialize state. if(keyInUse(key)) {
“ Method arguments often control behavior. ContactDetails details =
(ContactDetails) book.get(key);
“ Argument checking is one defensive book.remove(details.getName());
measure. book.remove(details.getPhone());
numberOfEntries--;
“ How to report illegal arguments? return true;
“ To the user? Is there a human user? } Diagnostic OK
else {
Can the user do anything to solve the problem? return false;
If not solvable, what should you suggest they do? } Diagnostic not OK
“ To the client object: }
return a diagnostic value, or throw an exception.

Client response to diagnostic Exception-throwing


“ Test the return value. “ Special feature of some languages
“ Attempt recovery on error. “ Java does provide exceptions
“ Avoid program failure. “ Advantages
“ Ignore the return value. “ No ‘special’ return value needed.
“ Errors cannot be ignored in the client.
“ Cannot be prevented.
“ Likely to lead to program failure.
“ Disadvantages (or are they?)
“ The normal flow-of-control is interrupted.
“ Exceptions are preferable. “ Specific recovery actions are encouraged.
Example of argument exception Error response and recovery
“ Clients should take note of error notifications.
public ContactDetails getDetails(String key)
{
“ Check return values.
if(key == null) { “ Don’t ‘ignore’ exceptions.
throw new NullPointerException(
"null key in getDetails"); “ Include code to attempt recovery.
} “ Will often require a loop.
if(key.trim().length() == 0) {
throw new IllegalArgumentException(
"Empty key passed to getDetails");
}
return (ContactDetails) book.get(key);
}

Example of recovery attempt Error avoidance


// Try to save the address book. “ Clients can often use server query methods
boolean successful = false;
int attempts = 0; to avoid errors.
do {
try {
“ More robust clients mean servers can be more
addressbook.saveToFile(filename); trusting.
successful = true; “ Unchecked exceptions can be used.
}
catch(IOException e) { “ Simplifies client logic.
System.out.println("Unable to save to " + filename);
attempts++; “ May increase client-server coupling.
if(attempts < MAX_ATTEMPTS) {
filename = an alternative file name;
}
}
} while(!successful && attempts < MAX_ATTEMPTS);
if(!successful) {
Report the problem and give up;
}
UML Activity
diagram

Construction inside objects

object internals

UML Activity diagram Pioneers – Edsger Dijkstra


“ Like flow charts “ Structured Programming
“ Activity as action states “ 1968, Eindhoven
“ Flow of control
“ Why are programmers so bad at
“ transitions
“ branch points understanding dynamic processes and
“ concurrency (fork & join) concurrency?
“ Illustrate flow of control “ (ALGOL then – but still hard in Java today!)
“ high level - e.g. workflow “ Observed that “go to” made things worse
“ low level - e.g. lines of
code
“ Hard to describe what state a process has
reached, when you don’t know which process is
being executed.
“ Define process as nested set of execution
blocks, with fixed entry and exit points
Top-down design & stepwise refinement Bottom-up construction
“ Why?
“ Start with what you understand
dispatch ambulance
“ Build complex structures from well-understood
parts
take 999 call identify region send ambulance “ Deal with concrete cases in order to understand
abstractions
“ Study of expert programmers shows that real
note patient allocate vehicle radio crew
estimate arrival software design work combines top-down and
condition
bottom up.
record address assign
find vehicle vehicle to call
in region

Modularity at code level Modularity in non-OO languages


“ Is this piece of code (class, method, function, “ Separate source files in C
procedure … “routine” in McConnell) “ Inputs, outputs, types and interface functions
needed? defined by declarations in “header files”.
“ Define what it will do “ Private variables and implementation details
defined in the “source file”
“ What information will it hide?
“ Inputs “ Modules in ML, Perl, Fortran, …
“ Outputs (including side effects) “ Export publicly visible interface details.
“ How will it handle errors? “ Keep implementation local whenever possible, in
interest of information hiding, encapsulation, low
“ Give it a good name coupling.
“ How will you test it?
“ Think about efficiency and algorithms
“ Write as comments, then fill in actual code
Source code as a design model Code as a structured model
public int Function_name (int parameter1, int parameter2)
“ Objectives:
// Function which doesn’t do anything, beyond showing the fact
“ Accurately express logical structure of the code // that different parts of the function can be distinguished.

int local_data_A;
“ Consistently express the logical structure int local_data_B;

“ Improve readability // Initialisation section


local_data_A = parameter1 + parameter2;
“ Good visual layout shows program structure local_data_B = parameter1 - parameter2;
local_data_B++;

“ Mostly based on white space and alignment // Processing


while (local_data_A < 40) {
“ The compiler ignores white space if ( (local_data_B * 2) > local_data_A ) then {
local_data_B = local_data_B – 1;
“ Alignment is the single most obvious feature to } else {
local_data_B = local_data_B + 1;
human readers. }
local_data_C = local_data_C + 1;
}
“ Like good typography in interaction design: return local_data_C;
}
but the “users” are other programmers!

Expressing local control structure Expressing structure within a line


while (local_data_C < 40) {
form_initial_estimate(local_data_C); “ Whitespacealwayshelpshumanreaders
record_marker(local_data_B – 1); “ newtotal=oldtotal+increment/missamount-1;
refine_estimate(local_data_A); “ newtotal = oldtotal + increment / missamount - 1;
local_data_C = local_data_C + 1;
} // end while “ The compiler doesn’t care – take care!
“ x = 1 * y+2 * z;
if ( (local_data_B * 2) > local_data_A ) then {
// drop estimate “ Be conservative when nesting parentheses
local_data_B = local_data_B – 1;
“ while ( (! error) && readInput() )
} else {
// raise estimate
local_data_B = local_data_B + 1; “ Continuation lines – exploit alignment
} // end if “ if ( ( aLongVariableName && anotherLongOne ) |
( someOtherCondition() ) )
{

}
Naming variables: Form Naming variables: Content
“ Priority: full and accurate (not just short) “ Data names describe domain, not computer
“ Abbreviate for pronunciation (remove vowels) “ Describe what, not just how
“ e.g. CmptrScnce (leave first and last letters) “ CustomerName better than PrimaryIndex
“ Parts of names reflect conventional functions “ Booleans should have obvious truth values
“ Role in program (e.g. “count”) “ ErrorFound better than Status
“ Type of operations (e.g. “window” or “pointer”) “ Indicate which variables are related
“ Hungarian naming (not really recommended): “ CustName, CustAddress, CustPhone
“ e.g. pscrMenu, ichMin
“ Identify globals, types & constants
“ Even individual variable names can exploit
“ C conventions: g_wholeApplet, T_mousePos
typographic structure for clarity
“ xPageStartPosition “ Even temporary variables have meaning
“ x_page_start_position “ Index, not Foo

Pioneers – Michael Jackson Structural roles of variables


“ Jackson Structured Programming “ Classification of what variables do in a routine
“ 1975, independent consultant, London “ Don’t confuse with data types (e.g. int, char, float)
“ Describe program structure according to the structure “ Almost all variables in simple programs do one of:
of input and output streams “ fixed value
“ stepper
“ Mostly used for COBOL file processing
“ most-recent holder
“ Still relevant to stream processing in Perl
“ most-wanted holder
“ Data records (items in collection, elements in array) “ gatherer
require a code loop “ transformation
“ Variant cases (subtypes, categories, enumerations) “ one-way flag
require conditional execution “ follower
“ temporary
“ Switching between code and data perspectives helps “ organizer
to learn about design complexity and to check “ Most common (70 % of variables) are fixed value,
correctness. stepper or most-recent holder.
Fixed value Stepper
“ Value is never changed after initialization “ Goes through a succession of values in some
systematic way
“ Example: input radius of a circle, then print area “ E.g. counting items, moving through array index
“ variable r is a fixed value, gets its value once, “ Example: loop where multiplier is used as a stepper.
never changes after that. “ outputs multiplication table, stepper goes through values
from one to ten.
“ Useful to declare “final” in Java (see variable PI).
public class AreaOfCircle {

public static void main(String[] args) { public class MultiplicationTable {


final float PI = 3.14F;
public static void main(String[] args) {
float r; int multiplier;
System.out.print("Enter circle radius: "); for (multiplier = 1; multiplier <= 10; multiplier++)
r = UserInputReader.readFloat(); System.out.println(multiplier + " * 3 = "
System.out.println(“Circle area is " + PI * r * r); + multiplier * 3);
} }
}
}

Most-recent holder Most-wanted holder


“ Most recent member of a group, or simply latest input “ The "best" (biggest, smallest, closest) of values seen.
value “ Example: find smallest of ten integers.
“ Example: ask the user for input until valid. “ Variable smallest is a most-wanted holder since it is given
“ Variable s is a most-recent holder since it holds the latest the most recent value if it is smaller than the smallest one so
input value. far.
“ (i is a stepper and number is a most-recent holder.)

public class AreaOfSquare { public class SearchSmallest {


public static void main(String[] args) {
int i, smallest, number;
public static void main(String[] args) { System.out.print("Enter the 1. number: ");
float s = 0f; smallest = UserInputReader.readInt();
while (s <= 0) { for (i = 2; i <= 10; i++) {
System.out.print("Enter side of square: "); System.out.print("Enter the " + i + ". number: ");
s = UserInputReader.readFloat(); number = UserInputReader.readInt();
} if (number < smallest) smallest = number;
System.out.println(“Area of square is " + s * s); }
System.out.println("The smallest was " + smallest);
}
}
} }
Gatherer Transformation
“ Accumulates values seen so far. “ Gets every value by calculation from the value of other
variable(s).
“ Example: accepts integers, then calculates mean. “ Example: ask the user for capital amount, calculate interest and
“ Variable sum is a gatherer the total of the inputs is gathered total capital for ten years.
in it. “ Variable interest is a transformation and is always calculated from
“ (count is a stepper and number is a most-recent holder.) the capital.
“ (capital is a gatherer and i is a counter.)

public class MeanValue { public class Growth {


public static void main(String[] args) {
public static void main(String[] argv) { float capital, interest; int i;
int count=0; System.out.print("Enter capital (positive or negative): ");
float sum=0, number=0; capital = UserInputReader.readFloat();
while (number != -999) { for (i = 1; i <=10; i++) {
System.out.print("Enter a number, -999 to quit: "); interest = 0.05F * capital;
number = UserInputReader.readFloat(); capital += interest;
if (number != -999) { sum += number; count++; } System.out.println("After "+i+" years interest is "
} + interest + " and capital is " + capital);
if (count>0) System.out.println("The mean is " + }
sum / count); }
} }
}

One-way flag Follower


“ Boolean variable which, once changed, never returns to its “ Gets old value of another variable as its new value.
original value. “ Example: input twelve integers and find biggest difference
“ Example: sum input numbers and report if any negatives. between successive inputs.
“ The one-way flag neg monitors whether there are negative “ Variable previous is a follower, following current.
numbers among the inputs. If a negative value is found, it will never
return to false. public class BiggestDifference {
“ (number is a most-recent holder and sum is a gatherer.) public static void main(String[] args) {
int month, current, previous, biggestDiff;
public class SumTotal { System.out.print("1st: "); previous = UserInputReader.readInt();
public static void main(String[] argv) { System.out.print("2nd: "); current = UserInputReader.readInt();
int number=1, sum=0; biggestDiff = current - previous;
boolean neg = false; for (month = 3; month <= 12; month++) {
while (number != 0) { previous = current;
System.out.print("Enter a number, 0 to quit: "); System.out.print(month + “th: ");
number = UserInputReader.readInt(); sum += number; current = UserInputReader.readInt();
if (number < 0) neg = true; if (current - previous > biggestDiff)
} biggestDiff = current - previous;
System.out.println("The sum is " + sum); }
if (neg) System.out.println(“There were negative numbers."); System.out.println(“Biggest difference was " + biggestDiff);
} }
} }
Temporary Organizer
“ Needed only for very short period (e.g. between two lines). “ An array for rearranging elements
“ Example: output two numbers in size order, swapping if “ Example: input ten characters and output in reverse order.
necessary. “ The reversal is performed in organizer variable word.
“ Values are swapped using a temporary variable tmp whose value is “ tmp is a temporary and i is a stepper.)
later meaningless (no matter how long the program would run).

public class Swap {


public static void main(String[] args) { public class Reverse {
int number1, number2, tmp; public static void main(String[] args) {
System.out.print("Enter num: "); char[] word = new char[10];
number1 = UserInputReader.readInt(); char tmp; int i;
System.out.print("Enter num: "); System.out.print("Enter ten letters: ");
number2 = UserInputReader.readInt(); for (i = 0; i < 10; i++) word[i] = UserInputReader.readChar();
if (number1 > number2) { for (i = 0; i < 5; i++) {
tmp = number1; tmp = word[i];
number1 = number2; word[i] = word[9-i];
number2 = tmp; word[9-i] = tmp;
} }
System.out.println(“Order is " + number1 + “," + number2 + "."); for (i = 0; i < 10; i++) System.out.print(word[i]);
} System.out.println();
} }
}

Verifying variables by role Type-checking as modeling tool


“ Many student program errors result from using “ Refine types to reflect meaning, not just to
the same variable in more than one role. satisfy the compiler (C++ example below)
“ Identify role of each variable during design
“ Valid (to compiler), but incorrect, code:
“ There are opportunities to check correct “ float totalHeight, myHeight, yourHeight;
operation according to constraints on role “ float totalWeight, myWeight, yourWeight;
“ Check stepper within range “ totalHeight = myHeight + yourHeight + myWeight;

“ Check most-wanted meets selection criterion “ Type-safe version:


“ De-allocate temporary value “ type t_height, t_weight: float;
“ t_height totalHeight, myHeight, yourHeight;
“ Confirm size of organizer array is invariant
“ t_weight totalWeight, myWeight, yourWeight;
“ Use compiler to guarantee final fixed value “ totalHeight = myHeight + yourHeight + myWeight;
“ Either do runtime safety checks (noting
efficiency tradeoff), or use language features. Compile error!
Language support for user types
“ Smalltalk
“ All types are classes – consistent, but inefficient
“ C++
“ Class overhead very low
“ User-defined types have no runtime cost
Construction of data lifecycles
“ Java
“ Unfortunately a little inefficient object state
“ But runtime inefficiency in infrequent calculations
far better than lost development time.

UML Statechart diagram UML Statechart diagram


“ Object lifecycle
“ data as state machine
“ Harel statecharts
“ nested states
“ concurrent substates
“ Explicit initial/final
“ valuable in C++
“ Note inversion of
activity diagram
Maintaining valid system state Pioneers – Tony Hoare
“ Pioneers (e.g. Turing) talked of proving “ Assertions and proof
program correctness using mathematics “ 1969, Queen’s University Belfast
“ In practice, the best we can do is confirm that “ Program element behaviour can be defined
the state of the system is consistent “ by a post-condition that will result …
“ State of an object valid before and after operation “ … given a known pre-condition.
“ Parameters and local variables valid at start and “ If prior and next states accurately defined:
end of routine
“ Individual elements can be composed
“ Guard values define state on entering & leaving
“ Program correctness is potentially provable
control blocks (loops and conditionals)
“ Invariants define conditions to be maintained
throughout operations, routines, loops.

Formal models: Z notation Formal models: Z notation

“ Definitions of the BirthdayBook state space:


“ known is a set of NAMEs “ An operation to change state
“ birthday is a partial map from NAMEs to DATEs “ AddBirthday modifies the state of BirthdayBook
“ Invariants: “ Inputs are a new name and date
“ known must be the domain of birthday “ Precondition is that name must not be previously known
“ Result of the operation, birthday’ is defined to be a new and
enlarged domain of the birthday map function
Formal models: Z notation Advantages of formal models
“ Requirements can be analysed at a fine level
of detail.
“ They are declarative (specify what the code
should do, not how), so can be used to check
specifications from an alternative perspective.
“ As a mathematical notation, offer the promise
“ An operation to inspect state of BirthdayBook of tools to do automated checking, or even
“ This schema does not change the state of BirthdayBook proofs of correctness (“verification”).
“ It has an output value (a set of people to send cards to)
“ They have been applied in some real
“ The output set is defined to be those people whose birthday
is equal to the input value today. development projects.

Disadvantages of formal models Language support for assertions


“ Notations that have lots of Greek letters and other “ Eiffel (pioneering OO language)
weird symbols look scary to non-specialists. “ supported pre- and post-conditions on every
“ Not a good choice for communicating with clients, users, method.
rank-and-file programmers and testers.
“ Level of detail (and thinking effort) is similar to that of “ C++ and Java support “assert” keyword
code, so managers get impatient. “ Programmer defines a statement that must
“ If we are working so hard, evaluate to boolean true value at runtime.
why aren’t we just writing the code? “ If assertion evaluates false, exception is raised
“ Tools are available, but not hugely popular.
“ Some languages have debug-only versions,
“ Applications so far in research / defence / safety critical
turned off when system considered correct.
“ Pragmatic compromise from UML developers
“ “Object Constraint Language” (OCL).
“ Dubious trade-off of efficiency for safety.
“ Formal specification of some aspects of the design, so that “ Variable roles could provide rigorous basis for
preconditions, invariants etc. can be added to models.
fine-granularity assertions in future.
Defensive programming
“ Assertions and correctness proofs are useful
tools, but not always available.
“ Defensive programming includes additional
code to help ensure local correctness
“ Treat function interfaces as a contract
Construction using objects
“ Each function / routine
“ Checks that input parameters meet assumptions components
“ Checks output values are valid
“ System-wide considerations
“ How to report / record detected bugs
“ Perhaps include off-switch for efficiency

UML Component diagram Component documentation


“ Your own classes should be documented the
same way library classes are.
“ Other people should be able to use your
class without reading the implementation.
“ Make your class a 'library class'!
Elements of documentation Elements of documentation
Documentation for a class should include: The documentation for each constructor and
“ the class name
method should include:
“ the name of the method
“ a comment describing the overall purpose
“ the return type
and characteristics of the class
“ the parameter names and types
“ a version number
“ a description of the purpose and function of
“ the authors’ names the method
“ documentation for each constructor and each “ a description of each parameter
method “ a description of the value returned

javadoc javadoc example


“ Part of the Java standard Class comment:
“ Each class and method can include special /**
keywords in a comment explaining the * The Responder class represents a response
interface to that class * generator object. It is used to generate an
* automatic response.
“ During javadoc compilation, the keyword *
information gets converted to a consistent * @author Michael Kölling and David J. Barnes
* @version 1.0 (1.Feb.2002)
reference format using HTML
*/
“ The documentation for standard Java
libraries is all generated using javadoc
javadoc example
Method comment:
/**
* Read a line of text from standard input (the text
* terminal), and return it as a set of words.
*
* @param prompt A prompt to print to screen.
Transition
* @return A set of Strings, where each String is
* one of the words typed by the user
*/ testing and optimisation
public HashSet getInput(String prompt)
{
...
}

What is the goal of testing? Testing and quality


“ A) To define the end point of the software “ Wikipedia
development process as a managed “ “Software testing is the process used to assess
objective? the quality of computer software. It is an empirical
technical investigation conducted to provide
“ B) To prove that the programmers have
stakeholders with information about the quality of
implemented the specification correctly? the product or service under test, with respect to
“ C) To demonstrate that the resulting software the context in which it is intended to operate.”
product meets defined quality standards? “ Edsger Dijkstra
“ D) To ensure that the software product won’t “ “Program testing can be used to show the
fail, with results that might be damaging? presence of bugs, but never to show their
absence”
“ E) None of the above?
Remember design as learning? Learning through testing
“ Design is the process of learning about a A bug is a system’s way of telling you that you
problem and describing a solution don’t know something (P. Armour)
“ at first with many gaps …
“ eventually in sufficient detail to build it. “ Testing searches for the presence of bugs.
“ We describe both the problem and the
solution in a series of design models.
“ Later: ‘debugging’ searches for the cause of
“ Testing those models in various ways helps
bugs, once testing has found that a bug
us gather more knowledge. exists.
“ Source code is simply the most detailed “ The manifestation of an bug as observable
model used in software development. behaviour of the system may well occur some
‘distance’ from its cause.

Testing principles Unit testing priorities


“ Look for violations of the interface contract. “ Concentrate on modules most likely to
“ Aim is to find bugs, not to prove that unit works as contain errors:
expected from its interface contract “ Particularly complex
“ Use positive tests (expected to pass) “ Novel things you’ve not done before
in the hope that they won’t pass “ Areas known to be error-prone
“ Use negative tests (expected to fail)
in the hope that they don’t fail
“ Some habits in unit test ordering
“ Start with small modules
“ Try to test boundaries of the contract
“ Try to get input/output modules working early
“ e.g. zero, one, overflow, search empty collection, “ Allows you to work with real test data
add to a full collection.
“ Add new ones gradually
“ You probably want to test critical modules early
“ For peace of mind, not because you expect errors
How to do it: testing strategies Pioneers – Michael Fagan
“ Manual techniques “ Software Inspections
“ Software inspections and code walkthrough “ 1976, IBM
“ Black box testing “ Approach to design checking, including
“ Based on specified unit interfaces, not internal planning, control and checkpoints.
structure, for test case design “ Try to find errors in design and code by
“ White box testing systematic walkthrough
“ Based on knowing the internal structure “ Work in teams including designer, coder,
“ Stress testing tester and moderator.
“ At what point will it fail?
“ ‘Random’ (unexpected) testing
“ Remember the goal: most errors in least time

Software inspections Inspection by yourself


“ A low-tech approach, relatively underused, “ Get away from the computer and ‘run’ a
but more powerful than appreciated. program by hand
“ Read the source code in execution order, “ Note the current object state on paper
acting out the role of the computer
“ Try to find opportunities for incorrect
“ High-level (step) or low-level (step-into) views.
behaviour by creating incorrect state.
“ An expert tries to find common errors
“ Array bound errors “ Tabulate values of fields, including invalid
“ Off-by-one errors combinations.
“ File I/O (and threaded network I/O) “ Identify the state changes that result from
“ Default values each method call.
“ Comparisons
“ Reference versus copy
Black box testing White box testing
“ Based on interface specifications for whole “ Design test cases by looking at internal
system or individual modules structure, including all possible bug sources
“ Analyse input ranges to determine test cases “ Test each independent path at least once
“ Boundary values “ Prepare test case data to force paths
“ Upper and lower bounds for each value “ Focus on error-prone situations (e.g. empty list)
“ Invalid inputs outside each bound “ The goal is to find as many errors as you can

“ Equivalence classes “ Control structure tests:


“ Identify data ranges and combinations that are “ conditions – take each possible branch
‘known’ to be equivalent “ data flow – confirm path through parameters
“ Ensure each equivalence class is sampled, but “ loops – executed zero, one, many times
not over-represented in test case data “ exceptions – ensure that they occur

Stress testing Random testing


“ The aim of stress testing is to find out “ There are far more combinations of state and
at what point the system will fail data than can be tested exhaustively
“ You really do want to know what that point is. “ Systematic test case design helps explore the
“ You have to keep going until the system fails. range of possible system behaviour
“ If it hasn’t failed, you haven’t done stress testing. “ But remember the goal is to make the system fail,
“ Consider both volume and speed not to identify the many ways it works correctly.
“ Note difference from performance testing, “ Experienced testers have an instinct for the
which aims to confirm that the system will kinds of things that make a system fail
perform as specified. “ Usually by thinking about the system in ways the
“ Used as a contractual demonstration programmer did not expect.
“ It’s not an efficient way of finding errors “ Sometimes, just doing things at random can be an
effective strategy for this.
Regression testing Regression testing
“ ‘Regression’ is when you go backwards, or “ Use a large database of test cases
things get worse “ Include all bugs reported by customers:
“ Regression in software usually results from re- “ customers are much more upset by failure of an
introducing faults that were previously fixed. already familiar feature than of a new one
“ Each bug fix has around 20% probability of “ reliability of software is relative to a set of inputs,
reintroducing some other old problem. so better test inputs that users actually generate!
“ Refactoring can reintroduce design faults “ Regression testing is boring and unpopular
“ So regression testing is designed to ensure “ test automation tools reduce mundane repetition
that a new version gives the same answers “ perhaps biggest single advance in tools for
as the old version did software engineering of packaged software

Test automation Unit testing


“ Thorough testing (especially regression “ Each unit of an application may be tested.
testing) is time consuming and repetitive. “ Method, class, interface, package
“ Write special classes to test interfaces of “ Can (should) be done during development.
other classes automatically “ Finding and fixing early lowers development costs
“ “test rig” or “test harness” (e.g. programmer time).
“ “test stubs” substitute for unwritten code, or “ Build up a test suite of necessary harnesses,
simulate real-time / complex data stubs and data files
“ Use standard tools to exercise external API, “ JUnit is often used to manage and run tests
commands, or UI (e.g. mouse replay) “ you will use this to check your practical exercises
“ In commercial contexts, often driven from build “ www.junit.org
and configuration tools.
Fixing bugs – ‘debugging’ Debugging strategy
“ Treat debugging as a series of experiments “ Your goal is to understand the nature of the
“ As with testing, debugging is about learning things error, not disguise the resulting symptom
“ Don’t just make a change in the hope that it “ Step 1: THINK
might fix a bug “ Which is the relevant data?
“ Form a hypothesis of what is causing the “ Why is it behaving that way?
unexpected behaviour “ Which part is correct, and which incorrect?
“ Make a change that is designed to test the “ Step 2: search and experiment
hypothesis
“ Backtrack from the place that is incorrect
“ If it works – good, the bug is fixed
“ If not – good, you’ve learned something “ Make tests on local state in each place
“ Either way, remember to check what else you “ Try to localise changes
broke

Print statements Debugging walkthroughs


“ The most popular debugging technique. “ Read through the code, explaining what state
“ No special tools required. changes will result from each line.
“ All programming languages support them. “ Explain to someone else what the code is

“ But often badly used …


doing.
“ They might spot the error.
“ Printing things at random in hope of seeing
something wrong “ The process of explaining might help you to spot it
for yourself (the cardboard software engineer)
“ Instead:
“ Can be done on-screen from source code, on
“ Make a hypothesis about the cause of a bug
paper (as in a software inspection), or using a
“ Use a print statement to test it
debugger
“ Output may be voluminous in loops
“ Turning off and on requires forethought.
Debuggers If all else fails …
“ Usual features include: “ Sleep on it.
“ Breakpoints
“ As with print statements, can be used to test state at a
particular program point, but can then also …
“ Step-over or step-into methods/routines
“ Identify specific routine or statement responsible for
unexpected effect.
“ Call sequence (stack) inspectors
“ Explore parameters preceding unexpected effect
“ Object and variable state inspectors
“ Also continuous “watch” windows.
“ However, debuggers are both language-
specific and environment-specific.

Classic testing advice Myers’ classic book


“ The Art of Software Testing
“ Glenford J. Myers
“ John Wiley, 1979
“ Seven Principles of Software Testing
“ Bertrand Meyer, ETH Zürich and Eiffel Software
“ IEEE Computer, August 2008, 99-101
“ Slightly interesting notes
“ Myers and Meyer are different people
“ Meyer was the inventor of the Eiffel language
Myers’ 10 principles Myers’ 10 principles (cont.)
“ A necessary part of a test case is a definition “ Test cases must be written for input
of the expected output or result. conditions that are invalid and unexpected, as
“ A programmer should avoid attempting to test well as for those that are valid and expected.
his or her own program. “ Examining a program to see if it does not do
“ A programming organisation should not test what it is supposed to do is only half the
its own programs. battle; the other half is seeing whether the
“ Thoroughly inspect the results of each test.
program does what it is not supposed to do.
“ Do not plan a testing effort under the tacit
assumption that no errors will be found.

Myers’ 10 principles (cont.) Meyer’s new classic article


“ Avoid throwaway test cases unless the
program is truly a throwaway program.
“ The probability of the existence of more
errors in a section of a program is
proportional to the number of errors already
found in that section.
“ Testing is an extremely creative and
intellectually challenging task.
Meyer’s 7 principles Meyer’s 7 principles (cont.)
“ Principle 1: Definition “ Principle 4: Applying ‘oracles’
“ To test a program is to try to make it fail. “ Determining success or failure of tests must be an
“ Principle 2: Tests versus specs automatic process.
“ Tests are no substitute for specifications. “ Principle 4 (variant): Contracts as oracles
“ Principle 3: Regression testing “ Oracles should be part of the program text, as
contracts. Determining test success or failure
“ Any failed execution must yield a test case, to should be an automatic process consisting of
remain a permanent part of the project’s test suite. monitoring contract satisfaction during execution.
“ Principle 5: Manual and automatic test cases
“ An effective testing process must include both
manually and automatically produced test cases.

Meyer’s 7 principles (cont.) Cost of testing


“ Principle 6: Empirical assessment of testing “ Testing can cost as much as coding
strategies “ Cost of rectifying bugs rises dramatically in
“ Evaluate any testing strategy, however attractive later phases of a project:
in principle, through objective assessment using “ When validating the initial design – moments
explicit criteria in a reproducible testing process.
“ When testing a module after coding – minutes
“ Principle 7: Assessment criteria “ When testing system after integration – hours
“ A testing strategy’s most important property is the “ When doing field trials – days
number of faults it uncovers as a function of time.
“ In subsequent litigation – years!
“ ...
“ Testing too late is a common failing
“ Save time and cost by design for early testing
When to stop testing When to stop testing
“ Imagine you are working on a project in which the “ Reliability growth model helps assess
timetable has allocated three months to testing. “ mean time to failure
“ When testing, you successfully find: “ number of bugs remaining
“ 400 bugs in the first month “ economics of further testing, .....
“ 200 bugs in the second month “ Software failure rate e-A/t
“ 100 bugs in the third month “ drops exponentially at first
“ What are the chances that you have found all the “ then decreases as K/T

bugs
bugs? k/T
“ Managing a large-scale testing process requires some kind
of statistical model. time spent testing
“ But changing testers brings new bugs to light
“ But not a good idea to use this as an incentive for
release targets, productivity bonuses etc
“ Programmers are smart enough to figure out basic statistics bugs tester
2 tester
if there is money involved. 3
tester
4
tester
1

Other system tests Testing efficiency: optimisation


“ Security testing “ Worst error is using wrong algorithm
“ automated probes, or “ e.g. lab graduate reduced 48 hours to 2 minutes
“ a favour from your Russian friends “ Try different size data sets – does execution time
vary as N, 2N, N2, N3, N4, kN ...?
“ Efficiency testing “ If this is the best algorithm, and you know it
“ test expected increase with data size scales in a way appropriate to your data, but
“ use code profilers to find hot spots still goes too slow for some reason, ask:
“ Usability testing “ How often will this program / feature be run?
“ essential to product success “ Hardware gets faster quickly
“ will be covered in further detail in Part II “ Optimisation may be a waste of your time
Testing efficiency: optimisation User interface efficiency
“ When optimisation is required “ Usability testing can measure speed of use
“ First: check out compiler optimisation flags “ How long did Fred take to order a book from
“ For some parts of extreme applications Amazon?
“ Use code profiler to find hotspots/bottlenecks “ How many errors did he make?
“ Most likely cause: overuse of some library/OS function
“ When pushing hardware envelope “ But every observation is different.
“ Cache or pre-calculate critical data “ Fred might be faster (or slower) next time
“ Recode a function in C or assembler “ Jane might be consistently faster
“ Use special fast math tricks & bit-twiddling
“ Unroll loops (but compilers should do this) “ So we compare averages:
“ But if this is an interactive system … “ over a number of trials
“ … how fast will the user be? “ over a range of people (experimental subjects)
“ Results usually have a normal distribution

Experimental usability testing Debugging user errors


“ Experimental treatment is some change that “ Assess a user’s conceptual model of system
we expect to have an effect on usability: “ Important to find typical sample users
“ Hypothesis: we expect new interface to be faster “ Users talk continuously while performing a
(& produce less errors) than old one defined experimental task: “think-aloud”
“ record to audio/video + screen capture
number of “ transcribed for detailed study of what user thinks
observation new old
trials is happening
“ code and classify events
“ look for breakdowns in usage/understanding.
time taken to order CD “ Can be used to assess usability of
(faster)
prototypes, even “paper prototypes”
“Expected answer: usually faster, but not always
Usability testing in the field
“ Brings advantages of ethnography /
contextual task analysis to testing phase of
product development.
“ Case study: Intuit Inc.’s Quicken product
“ originally based on interviews and observation
Iterative Development
“ follow-me-home programme after product release:
“ random selection of shrink-wrap buyers;
“ observation while reading manuals, installing, using. within any design phase or any
“ Quicken success was attributed to the combination of phases
programme:
“ survived predatory competition, later valued at $15
billion.

UML Deployment diagram The Waterfall Model


“ (Royce, 1970; now US DoD standard)

Requirements

Specification

Implementation
& unit testing
written in
user's Integration &
language system testing
written in
system Operations &
language maintenance

checks units
against
specification
Checks
requirements
are met
Spiral model (Boehm, 88) Prototyping
Increasing cost
Evaluate alternatives
Determine objectives,
and resolve risks
“ Supports early investigation of a system.
alternatives, Risk analysis
constraints “ Early problem identification.
Risk analysis “ Incomplete components can be simulated.
Operational
prototype
“ e.g. always returning a fixed result.
Prototype
Prototype 1 2 “ May want to avoid random or time-dependent
Requirements plan
behavior which is difficult to reproduce.
Software Detailed
Life-cycle plan requirements design “ Allows early interaction with clients
Development Requirements
plan validation Code
“ Perhaps at inception phase of project
Test “ Especially (if feasible) with actual users!
Integrate “ In product design, creative solutions are
Implement Develop and verify
Plan next phases next level product discovered by building many prototypes

Prototyping product concepts Prototypes without programming


“ Emphasise appearance of the interface, “ Low-fidelity prototypes (or mockups)
create some behaviour with scripting “ Paper-and-glue simulation of interface
functions: “ User indicates action by pointing at buttons on the
“ Visio – diagrams plus behaviour paper “screen”
“ Animation tools – movie sequence “ Experimenter changes display accordingly
“ JavaScript – simulate application as web page “ “Wizard of Oz” simulation method
“ PowerPoint – ‘click-through’ prototype “ Computer user interface is apparently operational
“ Cheap prototypes are good prototypes “ Actual system responses are produced by an
“ More creative solutions are often discovered by experimenter in another room.
building more prototypes. “ Can cheaply assess effects of “intelligent”
“ Glossy prototypes can be mistaken for the real interfaces
thing – either criticised more, or deployed!
Software continues changing Configuration management
“ Even after project completion! “ Version control
“ There are only two options for software: “ Change control
“ Either it is continuously maintained … “ Variants
“ … or it dies. “ Releases
“ Software that cannot be maintained will be
thrown away.
“ Not like a novel (written then finished).
“ Software is extended, corrected, maintained,
ported, adapted…
“ The work will be done by different people
over time (often decades).

Version control Change control


AFB fix: AFB fix: RJA fix:
Monday Tuesday Wed’day Thursday Friday Monday
Tuesday Wed’day Thursday
Vers 0.1 Vers 0.2 Vers 0.3 Vers 0.4 Cock-up! V0.1
V0.2a V0.3 V0.4??

RJA fix:
Tuesday
Week-End: V0.2b
Version 0.2
0.4
Alan’s work
is clobbered!!
“ Record regular “snapshot” backups
“ often appropriate to do so daily “ Essential in programming teams
“ Provides ability to “roll back” from errors “ Avoid the “clobbering” problem
“ Older tools (RCS, SCCS) rely on locking
“ Useful even for programmers working alone
“ More recent (CVS) automate merging
Variants from branch fixes Builds and Releases
1 2a 2a1 2a2 3 4 “ Record actual configuration of components that were
in a product release, or an overnight build integrating
single
2b 2b1 2b2 work of a large team.
update
split merge “ Allows problems to be investigated with the same source
two two code that was delivered or tested
updatesupdates
“ Often includes regression testing as part of build process
“ Branching (from local fixes) results in a tree of “ Also allow start of development on next release while
different versions or “variants” testing and supporting current release
“ Maintaining multiple branches is costly “ Universal requirement of commercial software development
(at least after release 1.0!)
“ Merge branches as often as possible “ Bug fixes made to 1.0.1 are also expected to be there in 2.0,
“ Minimise number of components that vary in each which requires regular merging
branch (ideally only one configuration file) “ Think about this: ‘About Internet Explorer’ reported:
“ If necessary, conditional compile/link/execution 6.0.2900.2180.xpsp2.070227-2254
can merge several variants into one

Localizing change Refactoring


“ One aim of reducing coupling and “ When classes are maintained, code is often
responsibility-driven design is to localize added.
change. “ Classes and methods tend to become longer.
“ When a change is needed, as few classes as “ Every now and then, classes and methods
possible should be affected. should be refactored to maintain cohesion
“ Thinking ahead and low coupling.
“ When designing a class, think what changes are “ e.g. move duplicated methods into a superclass
likely to be made in the future. “ Often removes code duplication, which:
“ Aim to make those changes easy. “ is an indicator of bad design,
“ When you fail (and you will), refactoring is “ makes maintenance harder,
needed. “ can lead to introduction of errors during
maintenance.
Refactoring and testing Beyond waterfalls and spirals
“ When refactoring code, it is very important to “ User-centred design
separate the refactoring from making other “ Participatory design
changes. “ Agile development: ‘XP’
“ First do the refactoring only, without changing the
functionality.
“ Then make functional changes after refactored
version shown to work OK.
“ Essential to run regression tests before and
after refactoring, to ensure that nothing has
been broken.

Participatory Design
User-centred Design
“ Focus on ‘end-users’, not just specifications “ Users become partners in the design team
from contract and/or client “ Originated in Scandinavian printing industry
“ Use ethnographic methods at inception stage “ Now used in developing world, with children, …
“ Design based on user conceptual models “ PICTIVE method
“ Early prototyping to assess conceptual model “ Users generate scenarios of use in advance
“ Low fidelity prototyping tools (simple office
“ Contextual evaluation to assess task
supplies) are provided for collaborative session
relevance “ The session is videotaped for data analysis
“ Frequent iteration
“ CARD method
“ Cards with screen-dumps on them are arranged
on a table to explore workflow options
Xtreme Programming’ (XP) Would XP have helped CAPSA?
“ Described in various books by Kent Beck “ Now Cambridge University Financial System
“ An example of an agile design methodology “ Previous systems:
“ Increasingly popular alternative to more “ In-house COBOL system 1966-1993
“corporate” waterfall/spiral models. “ Didn’t support commitment accounting
“ Reduce uncertainty by getting user feedback “ Reimplemented using Oracle package 1993
as soon as possible, but using actual code “ No change to procedures, data, operations

“ Typical team size = two (pair programming). “ First (XP-like?) attempt to change:
“ Constant series of updates, maybe even daily. “ Client-server “local” MS Access system
“ Respond to changing requirements and “ To be “synchronised” with central accounts
understanding of design by refactoring. “ Loss of confidence after critical review
“ When used on large projects, some evidence “ May 1998: consultant recommends restart
of XD (Xtreme Danger)! with “industry standard” accounting system

CAPSA project CAPSA mistakes


“ Detailed requirements gathering exercise “ No phased or incremental delivery
“ Input to supplier choice between Oracle vs. SAP “ No managed resource control
“ Bids & decision both based on optimism
“ No analysis of risks
“ ‘vapourware’ features in future versions
“ unrecognised inadequacy of research module “ No library of documentation
“ no user trials conducted, despite promise “ No direct contact with end-users
“ Danger signals “ No requirements traceability
“ High ‘rate of burn’ of consultancy fees “ No policing of supplier quality
“ Faulty accounting procedures discovered
“ New management, features & schedule slashed “ No testing programme
“ Bugs ignored, testing deferred, system went live “ No configuration control
“ “Big Bang” summer 2000: CU seizes up
CAPSA lessons UML review: Modelling for uncertainty
“ Classical system failure (Finkelstein)
“ More costly than anticipated
“ £10M or more, with hidden costs
“ Substantial disruption to organisation
“ Placed staff under undue pressure
“ Placed organisation under risk of failing to meet
financial and legal obligations
“ Danger signs in process profile
“ Long hours, high staff turnover etc
“ Systems fail systemically
“ not just software, but interaction with
organisational processes

The ‘quick and dirty’ version Software Design: beyond “correct”


“ Plan using general UML phase principles The requirements for design conflict and cannot be
reconciled. All designs for devices are in some
“ Make sure you visit / talk to end-users degree failures, either because they flout one or
“ show them pictures of proposed screens another of the requirements or because they are
compromises, and compromise implies a degree of
“ Write use case “stories” failure ... quite specific conflicts are inevitable once
“ note the parts that seem to be common requirements for economy are admitted; and conflicts
even among the requirements of use are not
“ Keep a piece of paper for each class unknown. It follows that all designs for use are
“ write down attributes, operations, relationships arbitrary. The designer or his client has to choose in
“ lay them out on table, and “talk through” scenarios what degree and where there shall be failure. … It is
quite impossible for any design to be the “logical
“ Think about object multiplicity and lifecycle outcome of the requirements” simply because, the
“ collections, state change, persistence requirements being in conflict, their logical outcome is
an impossibility.
“ Test as early as possible David Pye, The Nature and Aesthetics of Design (1978).

Das könnte Ihnen auch gefallen