1 / 23

Object-oriented design

Object-oriented design. Lectures 3 & 4. 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...

Download Presentation

Object-oriented design

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object-oriented design Lectures 3 & 4 • 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

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

  3. 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, m2acres etc

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

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

  6. Modularity - Example Building Apartment House Commercial building Two- Story house Low-rise apartment High-rise apartment Ranch Skyscraper

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

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

  9. Using these ideas in Java (& other OO languages) • Abstract • Encapsulated • Modular Object-oriented programming constructs to help you write code that is more... classes inheritanceinterfaces Java does not force you to write modular/abstract/encapsulated code You 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 we build in the practicals. Nevertheless, we’re going to insist you stick with these principles since they will be crucial in the future.

  10. 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 ¥ / £ £ / $ € / £

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

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

  13. Numeric progressions Example public 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(); } }

  14. Geometric progressions Example class GeomProgression extends Progression{ protected long inc; GeomProgression () { this(2);} GeomProgression (long base) { first = base; cur = first;} protected long nextValue() { cur *= first; return cur;} }

  15. Numeric progressions Example class 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;} }

  16. Inheritance diagram Class: Progression Class: ArithProgression Class: GeomProgression Class: FibonacciProgression Fields: long first, long cur Fields: long inc Fields: Fields: long prev Methods: Progression(), long firstValue(), long nextValue(), void printProgression(int) Methods: ArithProgression(), ArithProgression(long), long nextValue() Methods: GeomProgression(), GeomProgression(long), long nextValue() Methods: FibonacciProgression(), FibonacciProgression(long,long), long nextValue()

  17. Testing the progression classes class 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); } }

  18. Output Arithmetic 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

  19. 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 no method definitions -- just “signatures” indicating what 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...”

  20. Example - Inheritance interface CurrencyExchanger { double convert(double amount); } If your are building an accounting application that needs currency conversion, this interface specification tells you everything you need to know to decide whether these classes satisfy your requirements. You do not need to see code for a class that actually does the coversion....

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

  22. Example - 3 class 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); } } CurrencyExchanger GenericExchanger £/$ ¥/€

  23. Thinking like a computer scientist • Doctors see the world in terms ofillness, health, prevention, medicine, ... • Architects see the world in terms ofspaces, 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

More Related