DR Ian Reid B4, 4 Lectures, Hilary Term: Software Engineering
DR Ian Reid B4, 4 Lectures, Hilary Term: Software Engineering
http://www.robots.ox.ac.uk/~ian/Teaching/SoftEng
1. Software engineering
Mostly about concepts,
2. Structured programming
Revision, coding in C and Matlab, functions
3. Data structures
structures, classes
Learning Outcomes
The course will aim to give a good understanding of basic design methods, and emphasize the need to produce well-structured maintainable computer software. The course will concentrate on principles, but these will be reinforced with examples in Matlab and C/C++ programming languages. Specifically, by the end of the course students should: understand concepts of basic program design techniques that can be applied to a variety of programming languages, in particular Matlab and C/C++ understand the need for structured programming in software projects be able to recognise and to produce and/or maintain well structured programs have a basic understanding of the role of and advantages of object oriented design
Texts
Sommerville, Software Engineering, Addison-Wesley (8th edition), 2007. Wirth, Algorithms + Data Structures = Programs, Prentice-Hall, 1975 Leveson, Safeware: System Safety and Computers, Addison-Wesley, 1995. Lipmann and Lajoie, C++ Primer, Addison-Wesley, 2005. Goodrich et al., Data structures and algorithms in C++, Wiley, 2004
some examples
Example: Sizewell B
Nuclear power station (PWR), onstream in 1995 Software used extensively in the design Software for control!
first UK reactor to use software in its Primary Protection System)
Example: A380
A380 1400 separate programs There is a software project just to manage all the software! Clearly safetycritical features of the software
Example: NPfIT
NHS National Plan for IT Plan to provide electronic care records for patients Connect 30000 GPs and 300 hospitals Provide secure access to records for healthcare professionals Provide access for patients to their own records via Healthspace
Unity gain buffer Vout = Vin Very high input impedance, very low output impedance
Therac-25
2 people died and several others exposed to dangerous levels of radiation because of software flaws in radiotherapy device
OSIRIS
5M University financial package Expenditure to date more like 20-25M
NPfIT?
NHS 12 billion IT project
Software life-cycle
Software development stages
Specification Design Implementation Integration Validation Operation/Maintenance/Evolution
Different types of system organise these generic activities in different ways Waterfall approach treats them as distinct stages to be signed off chronologically In practice usually an iteration of various steps
Requirements
Vague initial goals Iterative refinement Leading to more precise specification Example
Calculate the n-bounce trajectory of a lossy bouncing ball. Refine this to consider What does the statement actually mean? Physics Initial conditions Air-resistance? Stopping criterion (criteria)? Now, think about how to design/implement
Validation/Verification
Verification: does the system confirm to spec? Validation: does it actually do what it was supposed to? Top-down vs bottom-up testing Black-box vs white-box testing Impossibility of exhaustive testing
Architectural design: identifying the building blocks Abstract specification: describe the data/functions and their constraints Interfaces: define how the modules fit together Component design: recursively design each block
Modular design
Algorithms Data structures
Programs
Structured programming
Top-down vs bottom-up Both are useful as a means to understand the relations between high-level and low-level views of a program Top-down
Code high level parts using stubs with assumed functionality for low-level dependencies Iteratively descend to lower-level modules
Bottom-up
Code and test each low-level component Need test harness so that low-level can be tested in its correct context Integrate components
Data flows
Data flow diagram Simple example, VTOL simulator
Controller
state thrust
Simulator
state
Display
These semantic concepts are implemented in different high-level programming languages using different syntax
int i; int tot = 0; int totsq = 0; for (i=1; i<N; i++) { tot += i; totsq += i*i; }
cout << tot << endl; cout << totsq << endl;
tot totsq
Matlab vs C
Matlab and C are both procedural languages Matlab is an interpreted language
each statement decoded and executed in turn
C is a compiled language
each module (.c file) is converted into assembly language The interfaces between the modules are Shared global data Function calls from one module to another This is resolved at link time when the modules are linked together into an executable
Procedural programming
Aim is to break program down into functional units
procedures or functions Set of inputs, set of outputs
In Matlab and C this procedural building block is the function Understanding functions
This script or function will typically call a bunch of other functions Functions are stored in .m files Multiple functions can be stored in one .m file, but only first is visible outside
The others are local functions Part of the recursive subdivision of the problem
FUNC
foo
bar
Organisation of C programs
Source code .c .cc compilation Object file .o Source code .. .c .cc compilation Object file .o linking
..
executable
Functions
Function definition Function call Function prototype Scope (local versus global data) Parameters and return value(s) Function call Low-level implementation of function calls Recursion
Function definition
% compute factorial function z = fact(n) % function body z = 1; for i=1:n z = z*i; end
// compute factorial int fact(int n) { int i, val = 1; for (i=1; i<=n; i++) { val *= i; } return val; }
Function call
Distinguish between
The function definition Defines the set of operations that will be executed when the function is called The inputs fact(10) The outputs And the function call a = 6; i.e. actually using the function z = fact(a);
[V,D] = eig(A);
Function prototype
The function prototype provides enough information to the compiler so that it can check that it is being called correctly Defines the interface
Input (parameter), output (return value)
myexp.h file
float myexp(float x);
myexp.c file
float myexp(float x) { const float precision = 1.0e-6; float term=1.0, res=0.0; int i=0; while (fabs(term)>precision) { res += term; i++; term = pow(x,i)/fact(i); } return res; }
Globals should be used with caution because their use inside a function compromises its encapsulation
Encapsulation
Want the function to behave in the same way for the same inputs
encapsulate particular functional relationship
But if the function depends on a global it could behave differently for the same inputs Live example using myexp
Function encapsulation
Input parameters
Output values
Hidden input
Input parameters
Output values
Hidden output
Side-effects
Could set value of a global variable in a function Again this compromises the functions encapsulation
Causes a side-effect An implicit output, not captured by the interface
Makes it difficult to re-use code with confidence c.f. C and Matlab function libraries
Set of re-usable routines with well defined interfaces
In small projects maybe not a big problem Hugely problematic in bigger projects, especially when multiple programmers working as a team Complicates interfaces between components, possibly in unintended ways
DATA
global variables
local variable m local variable 1 return location parameter x
Activation record
STACK
return value 1
Pass by value/reference
int i=5, j=10; swap(i,j); cout << i << << j << endl;
Pass by value
void swap(int a, int b) { int temp = a; a = b; b = temp; return; }
Pass by reference
void swap(int& a, int& b) { int temp = a; a = b; b = temp; return; }
Recursion
Recursion is the programming analogue of induction:
If p(0) and p(n) implies p(n+1) Then p(n) for all n
For example
Factorial: n! = n * (n-1)!, 0! = 1
Class definition
Controller
state thrust
Simulator
state
Display
State s;
Output parameters
Image ReadImage(const string filename, bool& flag);
function [Image, errflag] = ReadImage(filename) Basically the same, but cleaner in Matlab!
Arrays
An array is a data structure containing a numbered (indexed) collection of items of a single data type
int a[10]; res = a[0] + a[1] + a[2]; Complex z[20]; State s[100]; for (t=1; t<100; t++) { s[t].pos = s[t-1].pos + s[t-1].vel + 0.5*g; s[t].vel = s[t-1].vel + g GetThrust(s[t-1], burnrate)/s[t-1].mass; s[t].mass = s[t-1].mass burnrate*escapevel; }
Multi-dimensional arrays
double d[10][5];
has elements:
d[0][0] d[0][1] d[0][4] . . . d[9][0] d[9][1] d[9][4]
Methods
In C++ a class encapsulates related data and functions
A class has both data fields and functions that operate on the data
A class member function is called a method in the object-oriented programming literature
Example
class Complex { public: double re, im; double Mag() { return sqrt(re*re + im*im); }
Constructor
Whenever a variable is created (declared), memory space is allocated for it It might be initialised
int i; int i=10; int i(10);
In object-oriented programming, a class defines a black box data structure, which has
Public interface Private data
Other software components in the program can only access class through well-defined interface, minimising side-effects
Example
class Complex { public: Complex(double x, double y) { re=x; im=y; } double Re() { return re; } double Im() { return im; } double Mag() { return sqrt(re*re + im*im);} double Phase() { return atan2(im, re); } private: double re, im; };
Complex z(10.0,8.0); cout << Magnitude= << z.Mag() << endl; cout << Real part= << z.Re() << endl;
Example
class Complex { public: Complex(double x, double y) { r = sqrt(x*x + y*y); theta = atan2(y,x); } double Re() { return r*cos(theta); } double Im() { return r*sin(theta); } double Mag() { return r;} double Phase() { return theta; } }
private: double r, theta; };
Complex z(10.0,8.0); cout << Magnitude= << z.Mag() << endl; cout << Real part= << z.Re() << endl;
};
Object-oriented programming
An object in a programming context is an instance of a class Object-oriented programming concerns itself primarily with the design of classes and the interfaces between these classes The design stage breaks the problem down into classes and their interfaces OOP also includes two important ideas concerned with hierarchies of objects
Inheritance polymorphism
Inheritance
Hierarchical relationships often arise between classes Object-oriented design supports this through inheritance An derived class is one that has the functionality of its parent class but with some extra data or methods In C++
class A : public B { };
Example
class Window Data: width, height posx, posy
class InteractiveGraphicsWindow
Polymorphism
Polymorphism, Greek for many forms One of the most powerful object-oriented concepts Ability to hide alternative implementations behind a common interface Ability of objects of different types to respond in different ways to a similar event Example
TextWindow and GraphicsWindow, redraw()
Implementation
In C++ run-time polymorphism implemented via virtual functions class Window { virtual void redraw(); };
Example
Class A is base class, B and C both inherit from A If the object is of type A then call As func() If the object is of type B then call Bs func() If the object is of type C then call Cs func()
virtual void func() = 0;
If class A defines func() as then A has no implementation of func() class A is then an abstract base class
It is not possible to create an instance of class A, only instances derived classes, B and C class A defines an interface to which all derived classes must conform
Another example
Consider a vector graphics drawing package Consider base class Drawable
A graphics object that knows how to draw itself on the screen Class hierarchy may comprise lines, curves, points, images, etc
Program keeps a list of objects that have been created and on redraw, displays them one by one This is implemented easily by a loop
for (int i=0; i<N; i++) { obj[i]->Draw(); }
Templates
Templating is a mechanism in C++ to create classes in which one or more types are parameterised Example of compile-time polymnorphism
class BoundedArray { public: float GetElement(int i) { if (i<0 || i>=10) { cerr << Access out of bounds\n; return 0.0; } else { return a[i]; } } private: float a[10]; };
Templates
template <class Type> class BoundedArray { public: Type GetElement(int i) { if (i<0 || i>=10) { cerr << Access out of bounds\n; return Type(0); } else { return a[i]; } } private: Type a[10]; };
BoundedArray<int> x; BoundedArray<Complex> z;
Design patterns
Programs regularly employ similar design solutions Idea is to standardise the way these are implemented
Code re-use Increased reliability Fewer errors, shorter development time
Templates in C++ offer a way of providing libraries to implement these standard containers
STL supports
Stack (FILO structure) List (efficient insertion and deletion, ordered but not indexed) Vector (extendible array) others
STL example
std::vector<Type> is an extendible array It can increase its size as the program needs it to It can be accessed like an ordinary array (eg v[2]) It can report its current size
v.size()
You can add an item to the end without needing to know how big it is
v.push_back(x)
#include<vector>
int main() { std::vector<int> v; for (int i=0; i<20; i++) v.push_back(i); for (int i=0; i<v.size(); i++) std::cout << v[i] << std::endl; }
STL, continued
To create a new STL vector of a size specified at runtime int size; std::vector<Complex> z; std::cin >> size; z.resize(size);
z[5] = Complex(2.0,3.0);
STL, continued
To create a two dimensional array at run-time
x[2][3] = 10;
Iterators
A standard thing to want to do with a collection of data elements is to iterate over each
for (int i=0; i<v.size(); i++)
An iterator is a class that supports the standard programming pattern of iterating over a container type
std::vector<int> v; std::vector<int>::iterator i; for (it=v.begin(); it!=v.end(); it++)
Complete example
Design a program to compute a maze
User-specified size Print it out at the end
Algorithm
Mark all cells unvisited Choose a start cell While current cell has unvisited neighbours Choose one at random Break wall between it and current cell Recursively enter the chosen cell
Cell class
Accessor methods Break wall methods Wall flags Visited flag
Main program
int main(int argc, char* argv[]) { int width, height; cerr << "Enter maze width: "; cin >> width; cerr << "Enter maze height: "; cin >> height; Maze m(width, height); m.Compute(height-1,0); m.Print(); return 0; }
Concept summary
Top-down design
Abstraction Encapsulation / information hiding Modularity