CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose...

28
CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak www.cs.sjsu.edu /~mak

Transcript of CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose...

Page 1: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

CS 151: Object-Oriented Design November 5 Class Meeting

Department of Computer ScienceSan Jose State University

Fall 2013Instructor: Ron Mak

www.cs.sjsu.edu/~mak

Page 2: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

2

Cooking

CS 151 should be like a good cooking class.

It’s not about memorizinga bunch of recipes.

The goal is to learn tocook great meals.

Every time.

Page 3: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

3

Design is about Creativity

Don’t expect to be told explicitly and exactly what to do. That only happens in beginning programming classes.

Rely on your instincts to determine what’s good design in order to improve your programs. Learn and understand the basic design principles. Study examples of good design. Get lots of experience.

_

Page 4: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

4

What It’s All About

Just getting your program to work is not sufficient!

Documentation Functional Specification Design Specification

Good design Object-oriented

design principles Design patterns

Reliable Meets all requirements Works every time

Robust Tolerant of errors

Flexible Handle changes in design

Maintainable Long-lived programs New releases with

new features

Page 5: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

5

Favor Composition over Inheritance

Class hierarchies should not be complex! Don’t have over 5 or 6 levels. Otherwise, programmers may get lost in the hierarchy.

“Has a” (aggregation) is often more flexible than “is a” (inheritance) Use aggregation or composition to reduce the number of levels

in the class hierarchy and to add flexibility.

PersonWithAddress

Person

Professor Student

Person

Professor Student

Address

Street Email

Page 6: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

6

Why Favor Composition Over Inheritance?

An example of the Java library getting it wrong:

What’s wrong with this design? Oops:

public class Stack<T> extends Vector<T>{ T pop() { ... } void push(T item) { ... } ...}

Stack<String> st = new Stack<String>();st.push("A");st.push("B");st.push("C");st.remove(1); // Remove "B" in a non-stack way

Page 7: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

7

Why Favor Composition Over Inheritance?

The Stack class should have used aggregation instead of inheritance:

Now you can’t call remove() on a stack object._

public class Stack<T>{ private Vector<T> elements;

T pop() { ... } void push(T item) { ... } ... }

Page 8: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

8

Example: Inheritance vs. Composition

Consider the Point class:

Is it reasonable for Circle to extend Point?

public class Point { private int x; private int y;

public Point(int x, int y) { ... } public void translate(int dx, int dy) { ... } }

public class Circle extends Point{ private int radius;

public Circle(int x, int y, int radius) { ... } public void draw(Graphics g) { ... } }

Page 9: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

9

Example: Inheritance vs. Composition

Is it true that a circle “is a” point? No. A circle is not a point. It makes more sense for a circle to aggregate a point

as its center.

public class Circle{ private Point center; private int radius;

public Circle(Point center, int radius) { ... } public void draw(Graphics g) { ... } }

Page 10: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

10

Purpose of an Abstract Class

Unlike an interface, an abstract class can implement some or all of its methods. Therefore, like any other superclass, an abstract class can

contain common functionality for its subclasses.

An abstract class forces its subclasses to implement certain methods by declaring those methods to be abstract. Any subclass of the abstract class must implement

each of the abstract methods. Similar: Any class that implements an interface must implement

each of the interface’s methods._

Page 11: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

11

Important Facts about Abstract Classes

An abstract class cannot be instantiated. You cannot create an object directly from an abstract class. Therefore, if you do not want a class to be instantiated,

just declare it abstract even if it does not contain any abstract methods.

A variable’s type can be an abstract class. It can refer to an object instantiated from

a “concrete” subclass of the abstract class.

In UML class diagrams, the name of an abstract class and the name of an abstract method is in italics._

Page 12: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

12

Abstract Class Example

Chicken

void prepare()void cook()void serve()

Broccoli

void prepare()void cook()void serve()

PorkChops

void prepare()void cook()void serve()

Food

Food createFood(int type, ...)void prepare()void cook()void serve()

Food food = Food.createFood(type, ...);food.prepare();food.cook();food.serve();

Factory method

Abtract base class

Abstract methods

Abstracttype

Concreteobject

Concreteclasses

Page 13: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

13

Abstract Class Example

Each subclass of the abstract Food class must implement the abstract prepare(), cook(), and serve() methods.

Chicken

void prepare()void cook()void serve()

Broccoli

void prepare()void cook()void serve()

PorkChops

void prepare()void cook()void serve()

Food

Food createFood(int type, ...)void prepare()void cook()void serve()

Page 14: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

14

A Template Method

Suppose abstract class Foodhas a non-abstract methodmakeMeal().

The method calls each of the abstract methods in a given order. Each abstract method is implemented by a subclass. Method makeMeal() acts as a template for the subclasses by

calling their methods in a given order, no matter which subclass.

Chicken

void prepare()void cook()void serve()

Broccoli

void prepare()void cook()void serve()

PorkChops

void prepare()void cook()void serve()

Food

void makeMeal()void prepare()void cook()void serve()

public void makeMeal(){ prepare(); cook(); serve();}

Page 15: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

15

The Template Method Design Pattern

Context An algorithm (such as making a meal) is applicable for

multiple types (such as broccoli, chicken, or pork chops). The algorithm consists of primitive operations

(such as prepare, cook, and serve). The primitive operations can be different for each type

(cooking broccoli is different from cooking pork chops). However, the order of the operations doesn’t depend

on the type (first prepare, then cook, then serve). Solution

An abstract superclass has a method that executes the algorithm by calling abstract methods for the primitive operations in the right order.

Each subclass implements the methods for the primitive operations but not the overall algorithm.

Page 16: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

16

The Template Method Design Pattern, cont’d

Name in Design Pattern Actual Name

AbstractClass Food

ConcreteClass Broccoli, Chicken, PorkChop

templateMethod() makeMeal()

primitiveOp*() prepare(), cook(), serve()

From: Object-Oriented Design & Patterns, John Wiley & Sons, 2006.

Page 17: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

17

Quiz2013Nov05

Page 18: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

18

Refactoring

When you refactor a piece of code, you make a transformation that somehow improves the code. Restructure the code in a disciplined way. Don’t change the code’s behavior or introduce bugs.

Example 1 You have two similar classes with common functionality. Refactor by creating a superclass that contains the common

functionality. The two classes are its subclasses.

Example 2 Rewrite ugly

code forreadability.

car.translate(point.getX() – lastPoint.getX(), point.getY() – lastPoint.getY());

int dx = point.getX() – lastPoint.getX();int dy = point.getY() – lastPoint.getY();car.translate(dx, dy);

Page 19: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

19

Multiple Inheritance

Why doesn’t Java allow multiple inheritance? C++ does.

Multiple inheritance introduces many complexities that may not be worth the trouble. What if class Container and

class JComponent each has fields x and y? Then which fields does class JContainer inherit?

Java allows a class to implement multiple interfaces. What happens if two interfaces

have methods with the same name and signature?

From: Object-Oriented Design & Patterns, John Wiley & Sons, 2006.

Page 20: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

20

Geometric Shapes Class Hierarchy

From: Object-Oriented Design & Patterns, John Wiley & Sons, 2006.

Page 21: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

21

Rectangle2D is an Abstract Class

Rectangle2D.Float andRectangle2D.Double areinner classes.

public abstract class Rectangle2d extends RectangularShape{ ... public static class Float extends Rectangle2d { public float x, y; ... }

public static class Double extends Rectangle2d { public double x, y; ... }}

Rectangle2D rect = new Rectangle2D.Double( 5, 10, 15, 20);

From: Object-Oriented Design & Patterns, John Wiley & Sons, 2006.

An inner class that is static is called a nested class. A nested class does not require access to its surrounding scope.

Page 22: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

22

Exceptions Class Hierarchy

From: Object-Oriented Design & Patterns, John Wiley & Sons, 2006.

Page 23: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

23

Catching Exceptions

A catch clause gains control after the try block (or a method called from the try block) throws an exception object that belongs to the class of the catch clause. Or to one of its subclasses. Example: catch (IOException ex) will also catch

FileNotFoundException objects.

try { code that may throw exceptions } catch (ExceptionType1 exception1) { handler for ExceptionType1 } catch (ExceptionType2 exception1){ handler for ExceptionType2 } ...

Page 24: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

24

Original GoF Design Patterns

Creational patterns are ones that create objects for you, rather than having you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case.

Abstract Factory groups object factories that have a common theme.

Builder constructs complex objects by separating construction and representation.

Factory Method creates objects without specifying the exact class to create.

Prototype creates objects by cloning an existing object. Singleton restricts object creation for a class to only one

instance. http://en.wikipedia.org/wiki/Design_Patterns

Page 25: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

25

Original GoF Design Patterns, cont’d

Structural patterns are concerned with class and object composition. They use inheritance to compose interfaces and define ways to compose objects to obtain new functionality.

Adapter allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class. Note: The MouseAdapter class is not an example

of the Adapter Design Pattern Bridge decouples an abstraction from its implementation so

that the two can vary independently. Composite composes zero-or-more similar objects so that

they can be manipulated as one object. _

http://en.wikipedia.org/wiki/Design_Patterns

Page 26: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

26

Original GoF Design Patterns, cont’d

Structural patterns, cont’d

Decorator dynamically adds/overrides behaviour in an existing method of an object.

Facade provides a simplified interface to a large body of code. Flyweight reduces the cost of creating and manipulating a

large number of similar objects. Proxy provides a placeholder for another object to control

access, reduce cost, and reduce complexity. _

http://en.wikipedia.org/wiki/Design_Patterns

Page 27: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

27

Original GoF Design Patterns, cont’d

Behavioral patterns are specifically concerned with communication between objects.

Chain of responsibility delegates commands to a chain of processing objects.

Command creates objects which encapsulate actions and parameters.

Interpreter implements a specialized language. Iterator accesses the elements of an object sequentially

without exposing its underlying representation. Mediator allows loose coupling between classes by being the

only class that has detailed knowledge of their methods. Memento provides the ability to restore an object to its

previous state (undo). http://en.wikipedia.org/wiki/Design_Patterns

Page 28: CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak.

SJSU Dept. of Computer ScienceFall 2013: November 5

CS 151: Object-Oriented Design© R. Mak

28

Original GoF Design Patterns, cont’d

Behavioral patterns, cont’d

Observer is a publish/subscribe pattern which allows a number of observer objects to see an event.

State allows an object to alter its behavior when its internal state changes.

Strategy allows one of a family of algorithms to be selected on-the-fly at runtime.

Template method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.

Visitor separates an algorithm from an object structure by moving the hierarchy of methods into one object. _

http://en.wikipedia.org/wiki/Design_Patterns