l03 software design

53
Lecture 03 Software Design 1

Upload: olafur-andri-ragnarsson

Post on 13-Jan-2015

159 views

Category:

Software


3 download

DESCRIPTION

Hlutbundin forritun er öflug leið til að búa til hugbúnað. Hins vegar er auðvelt að gleyma eiginleikum hlutbundinna mála. Í þessum fyrri hluta um þetta efni munum við rifja upp hugtök eins og encapsulation, skil og polymorphma. Við munum líka skoða nokkur prinsipp eins og Separtaion of Concern (SoC). Í þessu fyrirlestri mun ég upplýsa leyndarmál sem aðeins góðir forritarar vita.

TRANSCRIPT

Page 1: L03 Software Design

Lecture 03Software Design 1

Page 2: L03 Software Design

Agenda Programming with Objects

– Classes– Interfaces– Generic programming– Reflection

Software Design– Ducks…

Page 3: L03 Software Design

Reading Barbin Introduction, 1 Core Principles

– Separation of concerns (SoC)– Coupling– Cohesion– Information Hiding

Don’t Repeat Yourself Polymorphism Optional:

– http://docs.oracle.com/javase/tutorial/

Page 4: L03 Software Design

Programming with Objects

Page 5: L03 Software Design

Object Oriented Programming Object Oriented programming can be powerful

– One of the best ways for general purpose computing

But– The power of object oriented languages needs to

be used properly!

However– Programmers tend to forget the power of OO

Page 6: L03 Software Design

Object Oriented Programming

Page 7: L03 Software Design

Object Oriented Programming Programming languages with objects

– Objects hold data and methods– Object variables (reference) point to objects

Object Oriented – Object are instances of classes, created with

new– Classes describe the objects– Classes extend other classes – inheritance– Instance variables are encapsulated– Methods manipulate instance variable

Page 8: L03 Software Design

Explain these concepts and why they are important in programmingEncapsulationInterfacesPolymorphism

EXERCISE

Page 9: L03 Software Design

Think About This! Object-oriented programming

– Is not about class inheritance and creating advanced class diagrams

Remember– Encapsulation – Hiding data– Interfaces – Hiding implementation– Polymorphism – Flexible and Generic Programming

Powerful programming– Separation of concerns– Separating what varies from what stays the same

Page 10: L03 Software Design

Think About This! Object-oriented programming

– Is not about class inheritance and creating advanced class diagrams

Remember– Encapsulation – Hiding data– Interfaces – Hiding implementation– Polymorphism – Flexible and Generic Programming

Powerful programming– Separation of concerns– Separating what varies from what stays the same

Page 11: L03 Software Design

Separate Variations Design Principle

Identify the aspects of your application that vary and separate them from what stays the same

Page 12: L03 Software Design

Don’t Repeat Yourself – DRY Single source of truth

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system

Page 13: L03 Software Design

Object Oriented Design Design of classes and interfaces

– Class diagram shows relationships– Sequence diagrams show flows

Design Patterns– Reoccurring solutions in design – “Best practices” – known solutions for common

problems

Page 14: L03 Software Design

Classes

Page 15: L03 Software Design

Objects Object created

Object used

Date day1; Date day2 = new Date();

System.out.println (new Date ()); String s = new Date().toString ();

day1 null

day2Date

Date now = new Date(); if (day2.before(now)) { System.out.println (day2.toString()); }

beforetostring...

Page 16: L03 Software Design

Objects Operator new creates

memory– String is an exception

Reference variablesalways point to some memory

day1 null

day2Date

beforetostring...

Date d = new Date();

Must be a concrete class

Can be any supertype or interface of the concrete class

Page 17: L03 Software Design

ClassesObject

+getId() : String

-id : int-name : String-username : String-password : String-email : String

User

Classes extend other classes– Concrete Inheritance– Subtype extends supertype

Class contains – Instance variables– Methods

Reference variables of type Object points to any class– Any supertype can reference subtype

Object obj = new User ();User u = (User)obj;

supertype

subtype

Page 18: L03 Software Design

Class methods Methods can be overridden

– Class extends a class and overrides a method Methods can be overloaded

– Same method with different parameters Methods can be

– public – any class can call the method– private – only available within the class– protected – only available within the class and

extended classes

Page 19: L03 Software Design

Class A inherits class B. A overwrites method f. Variable b is created like this:

B b = new A();What happens when this line is run:

b.f();

A) The method in A is runB) The method in B is runC) First the method in B is run, then the method in AD) The new statement is illegal and does not compile

QUIZ

Page 20: L03 Software Design

Class A inherits class B. A overwrites method f. Variable b is created like this:

B b = new A();What happens when this line is run:

b.f();

A) The method in A is runB) The method in B is runC) First the method in B is run, then the method in AD) The new statement is illegal and does not compile

QUIZ

Page 21: L03 Software Design

Classes References

– Point to concrete objects– Must be same type or supertype of concrete

object– Can be interface or abstract classObject obj = new Date ();Date d = (Date)obj;

Page 22: L03 Software Design

Constructors Classes have constructor

– Instantiation methods– Same name as the class

References– this – refers to the class– super – extended class

public Employee (String name, double salary){ this (name); this.salary = salary;}

public Manager (String name){ super (name, 0.0); ... }

Page 23: L03 Software Design

class Point{ private int x, y; public Point () { x = 0; y = 0; } public Point (int x, int y) { this.x = x; this.y = y; } public void move (intdx, intdy) { x+=dx;y+=dy; } public String toString () { return "(" + x + "," + y + ")"; }}

this used to refer to the class variables

Override toString method of Object

Class variablesDefault constructors

Overloaded constructor

Example

Page 24: L03 Software Design

Example

Bla

public class Test{ public static void main (String[] args) { System.out.println ("Test"); Test test = new Test(); } public Test () { Point p0; // null reference Point p1 = new Point (); Point p2 = new Point (1,2);

Object obj = p2; p0 = (Point)obj; p0.move (1, 1); System.out.println("p0=" + p0); }}

C:\java>javac Test.java

C:\java>java TestTestp0=(2,3)

X = 2Y = 3

Page 25: L03 Software Design

Java uses this method to pass objects reference to methods

A) Call by referenceB) Call by valueC) Call by method referenceD) Call by value reference

QUIZ

Page 26: L03 Software Design

Java uses this method to pass objects reference to methods

A) Call by referenceB) Call by valueC) Call by method referenceD) Call by value reference

QUIZ

Page 27: L03 Software Design

Call By Value Methods use call by value

– Object references are passed by value– The reference cannot change, but the object

can

x:

y:

42

0

Point

void changeReferance(Point p){ while (p.x>0) p.x--;}

p

Point p = new Point (42,0);changeReferance(p);System.out.println(p.x);

Reference p to PointLocal copy of a referencep to Pointp is same as this.p

p

Page 28: L03 Software Design

Inheritance Classes extend other classes

– Subclasses extend superclasses

Reference variables of super types can reference objects of subtypes

Employee

Manager

Empolyee e;e = new Employee(. . .)e = new Manager(. . .)

class Manager extends Employee{ ... }

Polymorphism

Page 29: L03 Software Design

public class Employee{ private String name; private double salary; private Date hireDate;

public Employee() { }

public Employee(String name, double salary, Date hireDate) { this.name = name; this.salary = salary; this.hireDate = hireDate; }

public Employee(String name) { this.name = name; }

Page 30: L03 Software Design

public String getName() { return name; }

public double getSalary() { return salary; }

public void setName(String name) { this.name = name; } public String toString() { return "Employee: " + getName(); }}

Page 31: L03 Software Design

Bla

class Manager extends Employee{ String title; double bonus; public Manager (String name, String title) { super (name); this.title = title; } public String getTitle () { return title; } public double getSalary() { return this.bonus + super.getSalery(); } public String toString () { return "Manager: " + getName() + ", " + getTitle (); }}

New method

New variables

Overridden methods

Page 32: L03 Software Design

What does this program print?public class Test2{ public static void main (String[] args) { System.out.println ("Test2"); Test2 test2 = new Test2(); } public Test2 () { Employee e0 = new Employee ("Dilbert"); Employee e1 = new Manager ("Pointy Haired", "Boss"); System.out.println("e0: " + e0); System.out.println("e1: " + e1); }}

C:\java>java Test2Test2e0: Employee: Dilberte1: Manager: Pointy Haired, Boss

EXERCISE

Page 33: L03 Software Design

Dynamic binding Decision on which method to run is taken

at runtime– The virtual machine uses a method table for

each classManager m = new Manager();m.setName(“P.H. Carl”); // Employee.setNamem.setTitle (“Boss”); // Manager.setTitlem.getSalary (); // Manager.getSalary

Employee e1 = new Manager("Pointy Haired", "Boss");e1.getSalary();

Is this manager salary with bonus?

Page 34: L03 Software Design

What does this program print?public class Test1{ public static void main(String[] args) { System.out.println("Test1"); new Test1(); }

public Test1() { Employee e0 = new Employee ("Dilbert"); Employee e1 = new Manager ("Pointy", "Boss"); System.out.println(e1.getTitle(); }} Trick question!

Does not compile since getTitle is not in Employee

EXERCISE

Page 35: L03 Software Design

class Manager extends Employee{ ... public double getSalary() { return this.bonus + super.getSalery(); }

Manager m = new Manager("Fay", "Boss"); m.setBonus(200);

// meantime, somewhere else Employee e = (Employee)something.getEmployees(); m.setSalary(100); System.out.println(e.getSalary()); // should print 100

Violates the Liskov substitution principle

WHAT IS POSSIBLE WRONG WITH THIS?

Page 36: L03 Software Design

Think About This! Why use Concrete Inheritance?

– Powerful implementation approach– Layered Supertype Pattern– Enables polymorphism if supertypes are used – New classes can be added without recompile

But remember– Object oriented programming is not just about

concrete inheritance– It has to be natural!– Class hierarchies are rigid– Not always good to force others to extend

Page 37: L03 Software Design

Abstract Classes Abstract classes put the responsibility of

implementation on subclasses– Classes extending an abstract class must

implement the abstract methods– Can contain both concrete and abstract

methods– Normal classes are concrete classes

Abstract classes cannot be instantiated Reference variables of abstract types are

allowed– Object must be a concrete class

Page 38: L03 Software Design

Abstract Exampleabstract class Person{ private String name; public Person(String name) { this.name = name; } // get and set methods ... public abstract String getDescription ();}class Employee extends Person{ public String getDescription() { return "Employee called " + super.getName(); }}

// Person p1 = new Person (); Does not work!Person p2;Person p3 = new Employee ("Dilbert");System.out.println (p3.getDescription());

Key Concept: Polymorphism

Page 39: L03 Software Design

Interfaces

Page 40: L03 Software Design

Interfaces Interface is a class without

implementation– Declaration of how to implement class– All methods and variables are static final

Classes implement interfaces– implements keyword– Must implement all the methods – or be

abstract

Page 41: L03 Software Design

Interfaces

public interface Comparable{ public int compareTo(Object other);}

class Employee extends Person implements Comparable{ public int compareTo(Object o) { ...

Page 42: L03 Software Design

Examplepublic interface Comparable{ public int compareTo(Object other);}

class Employee extends Person implements Comparable{ public int compareTo(Object o) { Employee e = (Employee)o; return this.getName().compareTo (e.getName()); } ...

Employee[] ale = new Employee[3]; ale[0] = new Employee ("Dilbert"); ale[1] = new Employee ("Wally"); ale[2] = new Employee ("Alice"); Arrays.sort(ale); for (int j=0; j <ale.length; j++) System.out.println(ale[j].getName());

AliceDilbertWally

How is this possible?

Page 43: L03 Software Design

Think About This! Class A calls class B -> A depends on B Class java.util.Arrays calls the

Employee.compareTo method Does Arrays depend on Employee?

Polymorphism

Separated interface

Page 44: L03 Software Design

Many Faces Arrays looks at the class as Comparable,

while we regard it as Employee

Class Employee implements Comparable{ ... compare

Class Arrays... sort(Object[] { Comparable c ...

Test...

Arrays.sort(persons

Arrays does NOT call Employee.compareTo, it calls Comaparable.compareTo which happens to be Employee Polymorphism

Page 45: L03 Software Design

Objects

class Employee extends Person

abstract class Person implements Comparable

class Manager extends Employee

Object o = new Manager()Person p = new Manager()Comparable c = new Manager()Employee e = new Manager()Manager m = new Manager()

Memory for Manager

reference

Must be concrete class

Can be any supertype

Page 46: L03 Software Design

Using Interfaces Interfaces cannot be instantiated

– Variables of interface types can reference objects that implement the interface

Interface can extend interfacespublic interface Powered extends Movable{ double milesPerGallon(); double SPEED_LIMIT = 95;}

Comarable c = new Comparable (); // NO!!!Comarable c = new Employee (); // OK!

Page 47: L03 Software Design

Why interfaces? Why not use abstract classes?

– Only one class can be extended– Class hierarchies are rigid and not always

suitable Interfaces can improve software design

– Provide abstraction – hide the implementation

– Classes that use interfaces are not dependant on a particular implementation

class Employee extends Person implements Comparable{ ...

Page 48: L03 Software Design

Example Pattern Table Data Gateway or Data Access Object

provide an interface to database table– Decision on what database access methods to

use can be configured

Example

public interface TeamDAO extends RuDAO{ public void addTeam (Team team); public Collection getTeams ();}

Inte

rface

ImplementationClientcode

Page 49: L03 Software Design

Example: Drawing systempublic interface Drawable{ public void draw ();}

public class Rectangle extends Shape{ private int h, w; public Rectangle (int x, int y, int h, int w) { this.x=x; this.y=y; this.h=h; this.w=w; } public void draw () { System.out.println ("Rectange (x="+x+",y="+y+",h="+h+",w="+w+")"); }}

public abstract class Shape implements Drawable{ protected int x,y;}

public class Circle extends Shape{ private int r; public Circle(int x, int y, int r) { this.x = x; this.y = y; this.r = r; } public void draw() { System.out.println ("Circle (x="+x+",y="+y+",r="+r+")"); }}

Page 50: L03 Software Design

Example: Drawing system Drawing all objects

– All draw objects implement Drawable

public DrawTest() { List<Drawable> l = new ArrayList<Drawable>();

l.add(new Rectangle(1, 1, 1, 1)); l.add(new Circle(2, 1, 1)); l.add(new Rectangle(8, 4, 1, 1));

for (Drawable d: l) { d.draw(); } }

Rectange (x=1,y=1,h=1,w=1)Circle (x=2,y=1,r=1)Rectange (x=8,y=4,h=1,w=1)

Page 51: L03 Software Design

Think About This! All drawing objects in this Layer extend Shape

Shape is abstract and implements Drawable

Client code does not know about the classes that implement Drawable

Shape is Layered Supertype

Shape is Template Method

Generic Programming

Page 52: L03 Software Design

X extends Y. Which is true? A) Correct if and only if X is a class and Y is an interfaceB) Correct if and only if X is an interface and Y is a classC) Correct if X and Y are either both classes or both interfacesD) Correct for all combinations of X and Y being classes and/or interfaces.

QUIZ

Page 53: L03 Software Design

X extends Y. Which is true? A) Correct if and only if X is a class and Y is an interfaceB) Correct if and only if X is an interface and Y is a classC) Correct if X and Y are either both classes or both interfacesD) Correct for all combinations of X and Y being classes and/or interfaces.

QUIZ