UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA...

62
1 CD Computer Science DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni [email protected]
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    217
  • download

    0

Transcript of UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA...

Page 1: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

1UCD Computer Science

DATA STRUCTURES AND ALGORITHMS I

WELCOME!

Dr ELENI MANGINA

[email protected]

Page 2: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

2UCD Computer Science

PracticalsSessions as assigned; attendance mandatoryEach will probably require:

2-4 hours prior to your session1.5 hours in lab2 hours after session

Several problems each, lifted directly from text-bookProgramming requires practice!45% of total course mark!Examination will require you understand the practicals!

1 week late? Maximum of 50% > 1 week late? No marks earned

Page 3: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

3UCD Computer Science

Practicals

Don’t cheat

Cooperation and group studying are encouraged.But it’s easy to detect, andCheating will be dealt with according to theDepartment’s harsh plagiarism policy.

Page 4: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

4UCD Computer Science

Course outline• Java refresher • Object-oriented and modular design • Mathematical tools for analyzing programs • Remaining weeks on a variety of useful topics

– Stacks– Queues– Lists– Vectors– Trees– Priority queues– Heaps

• Topics relevant to all programming languages 2001 is not just a course on “more Java”

A useful “bag of tools”that forms the foundationof all large software projects

Page 5: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

5UCD Computer Science

Textbook• Goodrich & Tomassia -- Buy it!

Many useful resources at book’s web site.

• You Must read assigned sections before corresponding lecture!– Otherwise you’ll be lost

Page 6: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

6UCD Computer Science

Java refresher• Forget Java over the summer? Try the notes, or any of

the excellent books or Web tutorials (see course Web for pointers)

• For Thursday: Read G&T Chapter 1• Start Practical #1• Some of the following details may be bewildering or

overly complicated at first -- come back to these notes or resources later when you understand what’s going on

Page 7: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

7UCD Computer Science

Basic Concepts• Classes: a conceptual “box” that holds data (“instance

variables”) and methods that can be invoked in the data.• Objects: instances of a given class• Types: classes + primitive types (int, float, ...) +

built-in data structures (array)• Methods: a.k.a. “functions”, “subroutines”• Access modifiers: public, private, static, …• Expressions: create new values from combinations of

existing values• Control flow: if, for, return, ...• Packages: how classes are organized

Page 8: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

8UCD Computer Science

Classesclass Fish {

int nfins; // instanceString name; // variables

Fish(int _nfins, String _name) { // constructornfins = _nfins; // methodname = _name;

}

void morefins(int delta) { // “regular” method

nfins += delta;}

}

Page 9: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

9UCD Computer Science

A complete program• A Java program doesn’t “do anything” unless is

contains a special main method:

class Fish {int nfins;String name;Fish(int _nfins, String _name) {

nfins = _nfins;name = _name;

}void morefins(int delta) {

nfins += delta;}public static void main(String args[]) {

Fish f = new Fish(3, "Fred"); // object creationf.morefins(4); // method invocationSystem.out.println("Fred has " + f.nfins + "fins");

}}

Page 10: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

10UCD Computer Science

Files, packages, classes• A single Java application typically comprises many

classes, grouped into several packages, much of which might be shared with other applications:

Payroll Program Human Resources Program

package A

package B

package C package DC1

C2

C4

C3

C6

C7

C5

C9

C10

C8

Page 11: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

11UCD Computer Science

Files, packages, classes - continued• There must be a 1-to-1 correspondence between:

Classes - Java source files Packages - directories comtaining the class files

/app/acounting/packageA/C1.java /C2.java /packageB/C3.java /C4.java /sharedstuff/packageC/C5.java /C6.java /C7.java /human-res/packageD/C8.java /C9.java /C10.java

Page 12: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

12UCD Computer Science

Creating objects and valuestype variablename = expression

int nfingers = 4;double weight; // very occasionally, initial value inappropriate/unnessaryboolean defective = weight<0; // initial value can be any expression

Integer ntoes = new Integer(4); // primitive data types aren’t objects

Boolean problem = new Boolean(defective || (nfingers<0);

String name = "Bob";

Fish f = new Fish(3, "Bob");

Page 13: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

13UCD Computer Science

Simple Input/Output• Java has an incredibly complicated hierarchy of classes for

performing input/output. • Output

System.out.println(f.name + " has " + f.nfins + " fins");

• Inputimport java.io.*; // enable access to all Java I/O classes

BufferedReader stdin =

new BufferedReader(new InputStreamReader(System.in));

String line = stdin.readLine(); // read 1 line of text

Next step depends on what data type the user is expected to enter. For example…int xnfins = Integer.valueOf(line).intValue(); // expecting an integer

… or … float weight = Float.valueOf(line).floatValue(); // expecting a float

Page 14: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

14UCD Computer Science

Exceptions• Any number of exceptional circumstances may

arise during program execution that cause troubleimport java.io.*;class IOExample { public static void main(String[] args) { try { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String line; System.out.print("Enter the number of fins > "); // wait til user enters something other than just RETURN while ((line=stdin.readLine()) == null) ; int nfins = Integer.valueOf(line).intValue(); } catch (IOException x) { // oops -- something strange went wrong System.out.println("Is your keyboard OK?! -- " + x); } catch (NumberFormatException x) { // entered something like “frog” System.out.println("Integers only! -- " + x); } }}

Page 15: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

15UCD Computer Science

Control flowif (nfins > 10) { // execute block only if condition holds

System.out.println(“Are you sure??!??!”);}

int a = 10, b = 20;while (a>0) { // repeatedly execute body until a=0

b = b+a;if (b > 60) break; // immediately terminate while loopa = a-1;

}// now a=5 and b=65for (int i = 0; i < b; i++) { // set i=0, 1, 2, …, 64

a++; // shorthand for “a = a+1”}// now a=70 (and b is still 65)

Page 16: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

16UCD Computer Science

Expressions• float appendageCost = (nfins + ntoes) * costPerAppendage;

• int remainder = numerator % divisor; // eg 5%2 = 1

• boolean probablySick = (whiteCellCount > 145);

• x = ++j; // increment j, and set x to the new value• y = j++; // increment j, and set y to the current value

• String fullname = firstname + " " + surname;

• double w = 45; // set w to the real number 45.0• int x = 45; // set x to the integer 45• double y = w/10; // set y = 4.5• double z = x/10; // set z = 4.0 not 4.5 !!??!!• double z = ((double)x)/10; // set z = 4.5

• int q = 3 + 4 * 5; // sets q to 23, not 60 !!?!?

Page 17: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

17UCD Computer Science

Arrays• Java has one built-in “primitive” data structure

• When array is created, its capacity must be specified (with any integer expression!) and then can’t change

System.out.println("Enter the number of cities >");

int ncities = Integer.valueOf(stdin.readLine()).intValue();

int rainfall[ncities];

String name[ncities];

for (int i = 0; i < cities.length; i++) {

System.out.print("City " + i + " name > ");

name[i] = stdin.readLine();

System.out.print("City " + i + " rainfall > ");

rainfall[i] = Integer.valueOf(stdin.readLine()).intValue();

}

(danger -- no exception handling for simplicity)

Page 18: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

18UCD Computer Science

Defining methodsclass Rectangle {

int height, width;

int area() {

return height*width;

}

void wider(int delta) {

width += delta;

}

void taller(int delta) {

height += delta;

}

RETURN-TYPE NAME( ARG1, ARG2, … ) {

BODY

}

}

Page 19: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

19UCD Computer Science

The Dereference (“Dot”) Operator• If X is an an object of some class C that contains

an instance variable Y, then X.Y accesses that value of Y in object X

• Methods work exactly the same way

• stdin.readLine().toLowerCase().indexOf(“dog”)

the next string entered at the keyboard

the keyboard standard-input object

the position in that string of the first occurrence of “dog”

the string formed by replacing all UPPER case letters with lower

Page 20: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

20UCD Computer Science

ARRAYS

public class ArrayDemo

{

public static void main(String[] args) {

int[] anArray; // declare an array of integers

anArray = new int[10]; // create an array of integers

// assign a value to each array element and print

for (int i = 0; i < anArray.length; i++) {

anArray[i] = i; System.out.print(anArray[i] + " ");

}

System.out.println();

}

}

Page 21: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

21UCD Computer Science

Array types

• An array is an ordered collection or numbered list of values. The values can be primitive values, objects or even other arrays, but all of the values in an array must be of the same type.– byte b; // byte is a primitive type

– Byte[] arrayOfBytes; //byte[] is an array type: array of byte

– Byte[][] arrayOfArrayOfBytes; // byte[][] is another is another type: array of byte[]

– Point[] points; //Point[] is an array of point objects

Page 22: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

22UCD Computer Science

Creating Arrays

• Use the “new” keyword

• Arrays do not need to be initialized like objects do, however, so you don’t pass a list of arguments between parentheses.

• BUT! You need to specify how many byte values you want it to hold.

• Once an array is created, it can never grow or shrink

• byte[] buffer = new byte[1024];

• string[] lines = new String[50];

Page 23: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

23UCD Computer Science

Using arrays• You use square brackets to access the individual values contained in

the array. The elements of an array are numbered sequentially, starting with 0. The number of an array element refers to the element. This number is often called the index, and the process of looking up a numbered value in an array is sometimes called indexing the array.

• To refer to a particular element of an array, simply place the index of the desired element in square brackets after the name of the array

String[] responses = new String[2]; //Create an array of two strings

responses[0] = “Yes”; //Set the first element of the array

responses[1] = “No”; //Set the second element of the array

//Now read these array elementsSystem.out.println(question + “(“ + response[0] + “/” + responses[1] + “ )”;

Page 24: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

24UCD Computer Science

Multidimensional arraysWhen the elements of an array are themselves arrays,

we say that the array is multi-dimensionalint[][] products = new products[10][10];• Declares a variable named products to hold an

array of arrays of int• Creates a 10-element array to hold 10 arrays of int• Creates 10 more arrays, each of which is a 10-

element array of int. It assigns each of these 10 new arrays to the elements of the initial array. The default value of every int element of each of these 10 new arrays is 0.

Page 25: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

25UCD Computer Science

Multidimensional arraysThe previous line is the same with the code

below:

int[][] products = new int[10][];

for (int i=0; i<10; i++)

products[i] = new int[10];

The new keyword performs the additional initialisation automatically for you

Float[][][] globalTemperatureData = new float[360][180][100];

Page 26: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

26UCD Computer Science

Multidimensional arraysInt[][] products = { {0,0,0,0,0},

{0,1,2,3,4},

{0,2,4,6,8},

{0,3,6,9,12},

{0,4,8,12,16} };

A 5x5 multiplication array

Page 27: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

27UCD Computer Science

Multidimensional arraysarraycopy() method:

char[] text = “Now is the time”;

char[] copy = new char[100];

System.arraycopy(text,4,copy,0,10);

//move some of the text to later elements,making room for instertions

System.arraycopy(copy,3,copy, 6,7)

Page 28: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

28UCD Computer Science

Multidimensional arraysimport java.util.Arrays;

int[] intarray = new int[] {10,5,7,-3}; //An array of integers

Arrays.sort(intarray); //sort it in place

int pos = Arrays.binarySearch(intarray, 7); //Value 7 is found at index 2

pos = Arrays.binarySearch(intarray,12); //not found, negative return value

//arrays of objects can be sorted and searched too

String[] strarray = new String[] { “new”, “is”, “the”, “time”);

Arrays.sort(strarray); //{“is”, “now”, “the”, “time”}

//arrays equals() compares all elements of two arrays

String[] clone = (String[]) strarray.clone();

boolean b1 = Arrays.equals(strarry, clone); // Yes, they are equal

//arrays.fill() initialises array elements

byte[] data = new byte[100]; //an empty array: elements set to 0

Arrays.fill(data, (byte) –1); //Set them all to –1

Arrays.fill(data,5,10,(byte) –2); //set elements 5,6,7,8,9 to -2

Page 29: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

29UCD Computer Science

Arrays

• Java has one built-in “primitive” data structure• When array is created, its capacity must be specified (with any integer expression!) and

then can’t change

System.out.println("Enter the number of cities >");int ncities = Integer.valueOf(stdin.readLine()).intValue();int rainfall[ncities];String name[ncities];for (int i = 0; i < cities.length; i++) {

System.out.print("City " + i + " name > ");name[i] = stdin.readLine();System.out.print("City " + i + " rainfall > ");rainfall[i] = Integer.valueOf(stdin.readLine()).intValue();

}

Page 30: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

30UCD Computer Science

Input and Output streams

The java.io package defines a large number of classes for reading and writing streaming, or sequential, data. The InputStream and OutputStream classes are for reading and writing streams, while the Reader and Writer classes are for reading and writing streams of characters. Streams can be nested, meaning you might read characters from a FilterReader object that reads and processes characters from an underlying Reader stream. This underlying Reader stream might read bytes from an InputStream and convert them to characters.

Page 31: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

31UCD Computer Science

Read lines of input the user typesimport java.io.*;

BufferedReader console = new Bufferedreader(new InputStreamReader(System.in));

System.out.print(“What is your name:”);

String name = null;

try {

name = console.readLine(); }

catch (IOException e) {name = “<“ + e + “>”;}

System.out.println(“Hello “ + name);

Page 32: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

32UCD Computer Science

Reading lines of text from a fileString filename = System.getProperty(“user.home”) + File.separator + “.cshrc”;try {

BufferedReader in = new BufferedReader(new FileReader(filename));String line;while((line = in.readLine()) !=null) {System.out.println(line);}in.close();}catch (IOException e) {//Handle FileNootFoundException etc..}

Page 33: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

33UCD Computer Science

Print text to Output Streamtry {

File f = new File(homedir, “.config”);

PrintWriter out = new PrintWriter(new FileWriter(f));

out.println(##Automatically generated config file. DO NOT EDIT”);

out.close(); //We’re done writing

}

catch (IOException e) {/*Handle exceptions*/}

Page 34: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

34UCD Computer Science

Not all files contain text, however. The following lines of code treat a file as a stream of bytes and read the bytes into a large array

try {

File f; //file to read

int filesize = (int) f.length(); //figure out the file size

byte[] data = new byte[filesize]; //create an array that is big enough

//create a stream to read the file

DataInputStream in = new DataInputStream(new FileInputStream(f));

in.readFully(data);

in.close();

}

catch (IOException e) {/*Handle exceptions */}

Page 35: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

35UCD Computer Science

How to use stream classes from java.util.zip to compute a checksum of data and then compress the data while writing it to a file

import java.io.*;

import java.util.zip.*;

try {File f; //file to write tobyte[] data; //data to writeChecksum check = new Adler32() //an object to compute a simple checksum//create a stream that writes bytes to the file fFileOutputStream fos = new FileoutputStream(f);//create a stream that compresses bytes and writes them to fosGZIPOutputStream gzos = new GZIPOutputStream(fos);//create a stream that computes a checksum on the bytes it writes to gzosCheckedOutputStream cos = new CheckedOutputStream(gzos,check);cos.write(data); //now write the data to the nested streamscos.close(); //close down the nested chain of streamslong sum = check.getValue(); //obtain the computed checksum}catch (IOException e) {/* handle exceptions */}

Page 36: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

36UCD Computer Science

Sample practical problem• R1.13 - write a Java function that takes an integer n and

returns the sum of the odd integers smaller than n.

class R113 {static int oddsum(int x) {

…return …;

}}

Assumption: presumably the sum of all positive ints x !

We need to loop over all odd integers less than x

We need a variable to store the sum

Page 37: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

37UCD Computer Science

R113 - continuedint sum = 0;

for (int i = 1; i<=x; i+=2) {… // i=1,3,5,…

}

Before proceeding… does this loop stop at the correct value of i??

Page 38: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

38UCD Computer Science

R113 - continuedint sum = 0;

for (int i = 1; i<x; i+=2) {sum += i;

}// now sum = sum of all odd integers less than x

Does this handle negative values of x properly?Does this handle zero properly?Does this handle one properly?

Hint: what is the minimum number of timesany “for” loop will execute!

Page 39: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

39UCD Computer Science

R113 - putting it all togetherclass R113 { static int oddsum(int x) { if (x<2) return 0; // special case! int sum = 0; for (int i=1; i<x; i+=2) { sum += i; } return sum; } public static void main(String[] args) { int i = 6; // “regular” input int osi = oddsum(i); System.out.println("got " + osi + " should be 9"); int j = -10; // problem with negative inputs? int osj = oddsum(j); System.out.println("got " + osj + " should be 0"); int k = 5; // problem with odd inputs? int osk = oddsum(k); System.out.println("got " + osk + " should be 4"); }}

Page 40: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

40UCD Computer Science

Object-oriented design• Learning the basic building blocks of programming is

straightforward...• On the other hand.... Designing/implementing large

software systems is part art, part craft, part science, and takes years to learn.

• Well-designed and built software is...– Correct - the code must do what it is supposed to– Efficient - it should do so as rapidly as possible– Reusable - the code should be sufficiently generic so that it can

be used again in related systems– Readable - humans read code too, not just machines!– Extensible - the code should be easily modified to handle

modified requirements ...

• Read Ch 2; complete Practical!

Page 41: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

41UCD Computer Science

Three Fundamental Ideas• Three ways to “think like a computer scientist” in

order to create high-quality software

– Abstraction

– Encapsulation

– Modularity

• These are perhaps the most fundamental ideas in all of computer science

Page 42: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

42UCD Computer Science

1. Abstraction• Abstraction = distill complex software system down to a its

fundamental/primitive components/properties/functions• Your simplified, abstract view of the problem will ignore (“abstract

away”) from [relatively] unimportant details and capture the “essense” of the problem

• Analogy. A good company manager doesn’t get bogged down in details, but rather has a high-level perspective. However: this works only when the lower-level processes are understoof well enough to know what can be ignored and what must be managed.

• Example. Write program to convert from €£¥$Don’t write one function to convert €£, another for €$, etcInstead write one generic conversion function that takes as a parameter the exchange rate

• Why? Correctness: easier to verify rounding is handled properly (only need to look at one function); Extensable: easier to add new currencies; Reusability: easier to extend to ºFºC, m2acres etc

Page 43: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

43UCD Computer Science

2. Encapsulation• Encapsulation = design code so that each component is a

“black box”: other components don’t need to know internal details in order to use on another

• Analogy. The manager of a hotel conference center relies on the Catering Dept, the Cleaning staff, the Audio/Visual staff. But she shouldn’t need to know in detail how these other organizations do their job (eg, which supplies the caterer uses, how many window cleaners the Cleaning dept employs, etc)

• Example. A application used by the Accounting department shouldn’t need to know anything about how the exchange rate function works in detail in order to invoke it.

• Why? Correctness: If acounting app relies on implementation details of the exchange rate, harder to to know that the acoutning software works properly; Extendability: If exhange rate is modified, then aounting app probably needs to be updated too, etc

Page 44: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

44UCD Computer Science

3. Modularity• Modular = program is organized so that the various

functions/properties are cleanly divided into separate units of code

• Analogy. The Cleaners, Caterers, Accountants, etc all have well-defined and distinct positions in the management hierarchy.

• Example. The exchange rate just converts prices -- it doesn’t print them, or store them in files, or verify them for accuracy, or compare them to competitor’s prices, or... These may all be essential funtions of the accounting software, but they must not be the responsibility of the exchange rate code.

• Why? Modularity makes it easier to validate, understand, extend, analyze, etc the system.

Page 45: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

45UCD Computer Science

Modularity - Example

Building

Apartment House Commercial building

SkyscraperTwo- Story house

RanchHigh-rise apartment

Low-rise apartment

Page 46: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

46UCD Computer Science

Modularity - example• “Write a function to compute the interest earned on an amount £p

invested at an annual rate of R% over a period of T years”• Right, good, modular, clean, organized, ...

double earnedInterest(double p, double r, int y) {if (y==0) return p;else return earnedInterest(p,r,y-1)*(1+r);

}

• Wrong, bad, unmodular, complicated, messy, ...double earnedInterest(double p, double r, int y) {if (y==0) { System.out.println(“No interest in first year”); return p;} else { double prev = earnedInterest(p,r,y-1); double new = prev*r; double tot = prev + new; System.out.println(“Interest from prev years = “ +

prev + “; year “ + y + “ = “ + new +“; total interest = “ + tot);

return totInterest;}

}

Page 47: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

47UCD Computer Science

Are these principles sacred?• These are principles (“modular designs are preferable”) , not laws

(“valid Java statements end with a semicolon”)

• Sometimes it is necessary to violate one or more of these principles (usually for the sake of efficiency)

• Analogy. The Cleaners and Caterers share a sink in order to save space & money, and Fred works for the Caterers in the afternoon and the Accounting Dept in the morning.

• Example. Suppose the Accounting app needs to calulate 10,000 exchange rates at a time. It is much to slow to invoke the exchange mechanism 10,000 separate times, so perhaps it should be extended to handle bulk transactions. Result: the exchange code is more complicated, harder to maintain, less generic -- but the benefit is probably worth the cost

Page 48: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

48UCD Computer Science

Using these ideas in Java (& other OO languages)

classesinheritanceinterfaces

Object-orientedprogrammingconstructs to helpyou write codethat is more...

•Abstract

•Encapsulated

•Modular

Java does not force you to write modular/abstract/encapsulated codeYou can get all the rope you want to hang yourself.

Designing good code takes more thought, and sometimes more code.The advantages won’t always be obvious in the tiny programs webuild in the practicals. Nevertheless, we’re going to insist you stickwith these principles since they will be crucial in the future.

Page 49: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

49UCD Computer Science

Inheritance• Data and functions are often hierachially structured

• OO inheritance constructs help you to directly encode such valuable information directly in your code

Simple conrete example: Figure 2.4

Numeric Conversion

Linear Conversion Logarthmic Conversion

£ / $ € / £¥ / £

For. Exch

F / C m2 /acres

Page 50: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

50UCD Computer Science

Dispatching & overloading• But what does inheritance really “mean”??!?

What do such classes “do”??!?• Answer: Given some object O of class C, if the code calls

function M on O (ie, “O.M()”) then:– 1. Look for a method M in C and execute it if found– 2. If M not found in C, try C’s superclass.– 3. Repeat step 2 all the way up the class hierarchy to the root, and

give error if M isn’t ever found

• “Overleading”: if M is defined more than once, only the definition closest to C is executed

• Overloading is an incredibly powerful tool for designing software: “A $/£ exchange rate mechanism is just like a generic linear converter, except for specific functions X, Y, Z.”

Page 51: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

51UCD Computer Science

Example• G&T pages 68-75: Numeric progressions• Simple incremental progression:

– 1, 1+1=2, 2+1=3, 3+1=4, 4+1=5, ...

• General arithmetic progression:– x, x+y, x+2y, x+3y, x+4y, x+5y, ...

• Geometric progression:– x, x2, x3, x4, x5, ...

• Fibonacci progression– x, y, x+y, x+2y, 2x+3y, 3x+5y, 5x+8y, ...

• Study this example until you vomit!

Page 52: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

52UCD Computer Science

Numeric progressions Examplepublic class Progression {

protected long first;protected long cur;Progression () {

cur = first = 0;}protected long firstValue() {

cur = first;return cur;}

protected long nextValue() {return ++cur;}

public void printProgression(int n) {System.out.print(firtsValue());for (int i=2; i <= n; i++) System.out.print(“ “ + nextValue());System.out.println();

}}

Page 53: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

53UCD Computer Science

Geometric progressions Exampleclass GeomProgression extends Progression{

protected long inc;

GeomProgression () {

this(2);}

GeomProgression (long base) {

first = base;

cur = first;}

protected long nextValue() {

cur *= first;

return cur;}

}

Page 54: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

54UCD Computer Science

Numeric progressions Exampleclass FibonacciProgression extends Progression{

long prev;

FibonacciProgression () {

this(0,1);}

FibonacciProgression (long value1, long value2) {

first = value1;

prev = value2 – value1;}

protected long nextValue() {

long temp = prev;

prev = cur;

cur += temp;

return cur;}

}

Page 55: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

55UCD Computer Science

Inheritance diagram

Class: Progression

Fields: long first, long cur

Methods: Progression(), long firstValue(), long nextValue(), void printProgression(int)

Class: ArithProgression

Fields: long inc

Methods: ArithProgression(), ArithProgression(long), long nextValue()

Class: GeomProgression

Fields:

Methods: GeomProgression(), GeomProgression(long), long nextValue()

Class: FibonacciProgression

Fields: long prev

Methods: FibonacciProgression(), FibonacciProgression(long,long), long nextValue()

Page 56: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

56UCD Computer Science

Testing the progression classesclass Tester{

public static vid main(String[] args) {

System.out.println(“Arithmetic progressions with default increment”) ;

prog = new ArithProgression();

prog.printProgression(10);

System.out.println(“Arithmetic progressions with increment 5:”) ;

prog = new ArithProgression(5);

prog.printProgression(5);

System.out.println(“Geometric progressions with default base”) ;

prog = new GeomProgression();

prog.printProgression(10);

System.out.println(“Geometric progressions with base 3:”) ;

prog = new GeomProgression(3);

prog.printProgression(3);

System.out.println(“Fibonacci progressions with default default start values”) ;

prog = new FibonacciProgression();

prog.printProgression(10);

System.out.println(“Fibonacci progressions with start values 4 and 6:”) ;

prog = new FibonacciProgression(4,6);

prog.printProgression(10);

}

}

Page 57: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

57UCD Computer Science

OutputArithmetic progression with default increment:

0 1 2 3 4 5 6 7 8 9

Arithmetic progression with increment 5:

0 5 10 15 20 25 30 35 40 45

Geometric progression with default base:

2 4 8 16 32 64 128 256 512 1024

Geometric progression with base 3:

3 9 27 81 243 729 2187 6561 19683 59049

Fibonacci progression with default start values:

0 1 1 2 3 5 8 13 21 34

Fibonacci progression with start values 4 and 6:

4 6 10 16 26 42 68 110 178 288

Page 58: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

58UCD Computer Science

Interfaces• Encapsulation says a class C should be a “black box” ---

class D that refers to class C needn’t know anything about the internal details of how C “does its job”

• Java interface construct enourages encapsulation: an interface is like a class, except there are nomethod definitions -- just “signatures” indicatingwhat methods can be invoked on classes that implement the interface

• Note that implementing an interface is completely different from extending a class!!– Implementing an interface means “I promise to support all of

the operations specified by the interface”– Extending a class means “I am similar to the parent class,

except in the following ways...”

Page 59: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

59UCD Computer Science

Example - Inheritance

interface CurrencyExchanger {double convert(double amount);

}

If your are building an accounting application that needscurrency conversion, this interface specification tells youeverything you need to know to decide whether theseclasses satisfy your requirements.

You do not need to see code for a class thatactually does the coversion....

Page 60: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

60UCD Computer Science

Example - 2

class SterlingToDollarExchanger implements CurrencyExchanger {SterlingToDollarExchanger() {}double convert(double amount) {

return amount*1.642;}

}

class YenToEuro Exchanger implements CurrencyExchanger {YenToEuroExchanger() {}double convert(double amount) {

return amount*0.00384;}

}

Oops!Duplicated code

Page 61: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

61UCD Computer Science

Example - 3class GenericExchanger implements CurrencyExchanger {

double rate;GenericExchanger(double _rate) {

rate = _rate;}double convert(double amount) {

return amount*rate; // only need to specify formula once!}

}class SterlingToDollarExchanger extends GenericExchanger {

SterlingToDollarExchanger() {super(1.642);

}}class YenToEuroExchanger extends GenericExchanger {

YenToEuroExchanger() {super(0.00384);

}}

GenericExchanger

¥/€£/$

CurrencyExchanger

Page 62: UCD Computer Science 1 DATA STRUCTURES AND ALGORITHMS I WELCOME! Dr ELENI MANGINA eleni.mangina@ucd.ie.

62UCD Computer Science

Thinking like a computer scientist• Doctors see the world in terms of

illness, health, prevention, medicine, ...• Architects see the world in terms of

spaces, buildings, ocupants, engineeringconstraints, ...

• Managers see the world in terms ofpeople, roles, tasks, shedules, skills,training, hierarchy, evaluation, ...

• Software engineers see the world in computational terms: components, interactions, objects, data, behavior, methods, abstractions, protocols, complexity, ...

• Soon you will too

They wouldn’t begood at their jobif they didn’t