Presentation is loading. Please wait.

Presentation is loading. Please wait.

NCCUCS Software Engineering 補充投影片 April 14, 2014.

Similar presentations


Presentation on theme: "NCCUCS Software Engineering 補充投影片 April 14, 2014."— Presentation transcript:

1 NCCUCS Software Engineering 補充投影片 April 14, 2014

2 An Example of OO Code Reuse

3 3 Forms of Software Reuse Source code –Copy-and-Paste  code duplication Result in high maintenance cost Binaries –Library –Framework Design patterns Specifications –Requirements, Functional, Design

4 4 Example: shapes displayed on the screen. class Rectangle { // 左上角座標 int x; int y; void move(int dx, int dy) { x = x + dx; y = y + dy; displayRect(); } void displayRect() { //refresh … } class Cirle { // 圓心座標 int x; int y; void move(int dx, int dy) { x = x + dx; y = y + dy; displayCircle(); } void displayCircle() { //refresh … } Class Parallelogram{ // 左上角座標 int x; int y; void move(int dx, int dy) { x = x + dx; y = y + dy; displayParallel(); } void displayParallel() { //refresh … } Rectangle CircleTriangle

5 What’s Wrong with it? This style is bad because … void display_all (Vector v) { // display all members (shapes) of Vector v for (i=0; i<v.length(); i++) { if v[i] instanceOf Rectangle ((Rectangle) v[i]).displayRect(); else if v[i] instanceOf Circle ((Circle) v[i]).displayCircle(); else if v[i] instanceOf Trangle ((Triangle) v[i]).displayTriangle(); else error(); } } // closed switch-cases What if a new kind of shape is required?

6 What’s Wrong with it? This style is bad because … (C# version) void display_all (Vector v) { // display all members (shapes) of Vector v for (i=0; i<v.length(); i++) { if (v[i] is Rectangle) ((Rectangle) v[i]).displayRect(); else if (v[i] is Circle) ((Circle) v[i]).displayCircle(); else if (v[i] is Trangle) ((Triangle) v[i]).displayTriangle(); else error(); } } // closed switch-cases What if a new kind of shape is required?

7 Bad Coding Style: Poor Extensibility What if a new kind of shape is required? Need to modify the source code, re-compile it If this occurs in many places in your code, …

8 8 Revised Example: shapes displayed on the screen. Use Inheritance Define the common code in an abstract class: Shape Shape RectangleCircleTriangle Rectangle Circle Triangle

9 9 Revised Example: shapes displayed on the screen. abstract class Shape { private int x, y; public Point where() { return new Point(x,y); } void move(int dx, int dy) { x = x + dx; // this.x = this.x + dx y = y + dy; display(); // this.display(); } abstract void display(); // to be defined later... // more instance variables and methods } // end of class Shape Rectangle Circle Triangle

10 10 Example continued: (method overriding) class Rectangle extends Shape { public void display() { //overriding the inherited “display”... // commands for displaying a rectangle }... // possibly, more methods and variables } class Circle extends Shape { public void display() { //overriding the inherited “ display ”... // commands for displaying an oval }... // possibly, more methods and variables } class Triangle extends Shape { public void display() { //overriding the inherited “ display ”... // commands for displaying a rounded rectangle }... // possibly, more methods and variables }

11 11 Dynamic Method Binding oneShape.move(2,3);Automatic method dispatching based on actual type of the object receiving the message Shape oneShape; //declared type Point newpt; oneShape = new Rectangle(); oneShape.move(2,3); –The effect of the last statement above is x = x + 2; y = y + 3; display(); // this refers to the rectangle object // 代父出征 this.display(); => display(this); // and “this” refers to an Rectangle object

12 12 Polymorphism and OO Reuse OOP is the ability to write a single piece of code that will operate on many different data types, some of which may not have been defined yet. Later, we may add a new kind of Shape and reuse ‘ move_all ’ without any change. class Parallelogram extends Shape { public void display() {... }... } Existing (old) code New code call v[i].move(dx, dy); void move_all (Vector v, int dx, int dy) { / / move all members (shapes) of Vector v by dx, dy for (i=0; i<v.length(); i++) v[i].move(dx, dy); // don’t care the exact class of Shapes }

13 Code Reuse Binary (Black box) reuse –import compiled classes/functions from a library Traditional code reuse OO Code reuse Existing (old) code New code Existing (old) code New code

14 Object-Oriented (Application) Frameworks Framework: architecture + implementation + hooks. The framework serves as the basis for many applications. Developers fill in the hooks to produce a new app. Framework Hooks Framework New Applications A framework is a reusable, semi-complete application that can be specialized to produce custom applications

15 Framework Concepts Applications customize and extend frameworks, much like a class inherits from it’s parent class. The architecture and implementation of the framework impose restrictions on the application. Framework Application Parent Subclass

16 Frameworks vs. Libraries Applications call library functions. Frameworks call application extensions. “Don’t call us, we’ll call you.” (call back) LibraryApplication FrameworkApplication Hollywood Principle

17 An Exercise of OOD 航空公司 會員里程累計優惠活動

18 Customer Purchase amount to get one point Number of points to get a free trip Regular$20 Same region: 1500 Further away: 3500 Same continent: 10500 Out-of-continent: 25000 Gold$18 Same region: 1300 Further away: 3100 Same continent: 10000 Out-of-continent: 22000 Platinum Note: Platinum customers get to choose a charity. RTM will give 1% of all purchases to that charity. $15Same region: 1200 Further away: 2850 Same continent: 9500 Out-of-continent: 20000 Frequent Flyer Program

19 Use a Single Class: Customer Class Customer { // type code String custType; // Regular, Gold, Platinum int custID; int points; // 累積點數 String name; public String getType() { … } public int getCustID() { … } public int getPoints() { … } public String getName() { … } // 增加累積點數 public void addPoints(int purchaseAmount) { … } // 以點數兌換機票 public int redeemPoints(int zone) {… } … }

20 依票價累積點數 // 依 purchaseAmount 增加點數 public void addPoints(int purchaseAmount) { if (getType().equals("REGULAR")) setPoints( getPoints() + purchaseAmount / 20 ) ; else if (getType().equals("GOLD")) { setPoints( getPoints() + purchaseAmount / 18) ; else if (getType().equals("PLATINUM")) { setPoints( getPoints() + purchaseAmount / 15) ; }

21 public int redeemPoints(int zone) { int pts = 0; if(getType().equals("REGULAR")) { switch(zone) { case 1: pts=1500; break; case 2: pts=3500; break; case 3: pts=10500; break; case 4: pts=25000; break; default: return 0; } } else if (getType().equals("GOLD")) { switch(zone) { case 1: pts=1300; break; case 2: pts=3100; break; case 3: pts=10000; break; case 4: pts=22000; break; default: return 0; } } else if (getType().equals("PLATINUM")) { switch(zone) { case 1: pts=1200; break; case 2: pts=2850; break; case 3: pts=9500; break; case 4: pts=20000; break; default: return 0; } 將已累積的點數 兌換機票,不同 區域需要不同的 點數 if(getPoints() < pts) return 0; setPoints(getPoints()-pts); return pts; }

22 What’s wrong with this program? Closed switch-case: Not extensible (object-oriented). How to revise it?

23 1. Replace Type Code with Subclasses To be overridden To be Reused

24 24 Customer --customerID -name -points +addPoints() +redeemPoints() +getPointFactor() +getZoneThreshold() GoldCustomer +getPointFactor() +getZoneThreshold() PlatinumCustomer -charity +getPointFactor() +getZoneThreshold() 1. Replace Type Code with Subclasses To be overridden To be Reused

25 public class Customer { // regular customers public int getPoints(); public void setPoints(int number); public int addPoints(int purchaseAmount) { int pts = 0; pts = purchaseAmount/getPointFactor(); setPoints(getPoints() + pts); return pts; } public int redeemPoints(int zone) { int pts = getZoneThreshold(zone); if(getPoints() < pts) return 0; setPoints(getPoints()-pts); return pts; } protected int getPointFactor() { return 20; } protected int getZoneThreshold(int zone) { switch(zone) { case 1: return 1500; case 2: return 3500; case 3: return 10500; case 4: return 25000; default: return Integer.MAX_VALUE; } Is this switch-case OK?

26 public class GoldCustomer extends Customer { protected int getPointFactor() { return 18; } protected int getZoneThreshold(int zone) { switch(zone) { case 1: return 1300; case 2: return 3100; case 3: return 10000; case 4: return 22000; default: return Integer.MAX_VALUE; }

27 public class PlatinumCustomer extends Customer { //public abstract String getCharity(); //public abstract void setCharity(String charity); protected int getPointFactor() { return 15; } protected int getZoneThreshold(int zone) { switch(zone) { case 1: return 1200; case 2: return 2850; case 3: return 9500; case 4: return 20000; default: return Integer.MAX_VALUE; }

28 2. Change of CustTypes A customer’s membership can be upgraded from ‘regular’ to ‘gold’ to ‘platinum’. The previous design: GoldCustomer c = new GoldCustomer(); cannot be changed. How to accommodate such changes?

29 2. Replace Type Code with a State Field Customer Membership type … Membership Gold getPointFactor() getZoneThreshold() Platinum getPointFactor() getZoneThreshold() … void setType (MemberShip m) … Regular getPointFactor() getZoneThreshold() getPointFactor() getZoneThreshold()

30 Exercise Finish the Frequent Flyers exercise using the second change: replace type code with a state field. –main: FrequentFlyers class –And other classes ( Customer, …) –With a few customer object instances to test your code –No need to have ‘charity’ stuff in the Platinum class

31 Abstractions in Programming Need PL support

32 Examples of Not Abstract Copy Read Keyboard Write Printer void Copy(){ int c; while ((c = ReadKeyboard()) != EOF) WritePrinter(c); } Write Disk enum OutputDevice {printer, disk}; void Copy(OutputDevice dev){ int c; while((c = ReadKeyboard())!= EOF) if(dev == printer) WritePrinter(c); else WriteDisk(c); } What’s wrong? A: ‘copy’ depends on the devices. Poor extensibility/reusability.

33 Another Example

34 Fix: Be Abstract and Reusable Flexible and reusable code void p( anArray, top) { … anArray[top++] = exp; … } void p( aStack) //type { … aStack.push(exp); … } versus 對 input parameters 假設愈少,重用度愈高 Recall:

35 The Copy Example Revisited Copy ReaderWriter Keyboard Reader Printer Writer Disk Writer abstract class Reader { // or interface abstract public int read(); }; abstract class Writer { // or interface abstract public void write(int); }; void copy(Reader r, Writer w){ int c; while((c = r.read()) != EOF) w.write(c); } Finding the underlying abstractions

36 The Regulate Example Revisited

37 Reference: Java Interfaces Note that the word “interface” –Is a specific term for a language construct –Is not the general word for “communication boundary” –Is also a term used in C#, UML (but not in C++)

38 Defining an Interface Java code: interface Queue { void add (Object obj); Object remove(); int size(); } Nothing about implementation here! –methods and no fields –Only static final fields (constants) allowed

39 Implementing an Interface class ArrayList implements Queue { void add (Object obj) { … } Object remove() { … } int size() { … } … }

40 Using Objects by Interface (As a Type) Say we had two implementations of Queue: Queue q1 = new CircularArrayQueue(100); or Queue q1 = new LinkedListQueue(); q1.add( new Widget() ); Queue q3 = new … Queue q2 = mergeQueue(q2, q3); We’ll talk more about interfaces next time.

41 Design guideline: Depend on Abstractions

42 Sorting as an Example Consider the two signature for ‘sort’: –void sort( aVector ) –void sort(aVector, aComparator) we need a comparison method to support sort, but sorting should NOT depend on a particular comparison method.

43 Appendix: Comparable vs. Comparator Interfaces in Java java.lang.Comparable: int compareTo(Object o1) This method compares this object with o1 object. Returned int value has the following meanings. –positive – this object is greater than o1 –zero – this object equals to o1 –negative – this object is less than o1 java.lang.Comparator: int compare(Object o1, Objecto2) This method compares o1 and o2 objects. Returned int value has the following meanings. –positive – o1 is greater than o2 –zero – o1 equals to o2 –negative – o1 is less than o1 public class Employee implements Comparable { private int empId; private String name; private int age; // getters & setters public int compareTo(Object o) { return this.empId – ((Employee)o).empId ; } } public class EmpSortByEmpId implements Comparator { public int compare(Object o1, Object o2) { return ((Employee)o1).getEmpId() – ((Employee) o2).getEmpId(); } } http://lkamal.blogspot.com/2008/07/java-sorting-comparator-vs-comparable.html


Download ppt "NCCUCS Software Engineering 補充投影片 April 14, 2014."

Similar presentations


Ads by Google