Top Banner
1 D Computer Science COMP-2001 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 ... This week : read Ch 2; complete Prac#1; prepare for Prac#2 Lectures 3 &
23

UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

Dec 20, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

1UCD Computer Science COMP-2001

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

• This week: read Ch 2; complete Prac#1; prepare for Prac#2

Lectures 3 & 4

Page 2: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

2UCD Computer Science COMP-2001

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 3: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

3UCD Computer Science COMP-2001

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 4: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

4UCD Computer Science COMP-2001

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 5: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

5UCD Computer Science COMP-2001

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 6: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

6UCD Computer Science COMP-2001

Modularity - Example

Building

Apartment House Commercial building

SkyscraperTwo- Story house

RanchHigh-rise apartment

Low-rise apartment

Page 7: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

7UCD Computer Science COMP-2001

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 8: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

8UCD Computer Science COMP-2001

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 9: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

9UCD Computer Science COMP-2001

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 10: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

10UCD Computer Science COMP-2001

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 11: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

11UCD Computer Science COMP-2001

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 12: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

12UCD Computer Science COMP-2001

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 13: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

13UCD Computer Science COMP-2001

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 14: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

14UCD Computer Science COMP-2001

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 15: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

15UCD Computer Science COMP-2001

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 16: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

16UCD Computer Science COMP-2001

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 17: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

17UCD Computer Science COMP-2001

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 18: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

18UCD Computer Science COMP-2001

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 19: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

19UCD Computer Science COMP-2001

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 20: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

20UCD Computer Science COMP-2001

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 21: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

21UCD Computer Science COMP-2001

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 22: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

22UCD Computer Science COMP-2001

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 23: UCD Computer Science COMP-2001 1 Object-oriented design Learning the basic building blocks of programming is straightforward... On the other hand.... Designing/implementing.

23UCD Computer Science COMP-2001

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