systems analysis & design methods

28
Systems Analysis & Systems Analysis & Design Methods Design Methods VIII More OOD issues: VIII More OOD issues: Patterns & Testing Patterns & Testing

Upload: valencia-cruz

Post on 03-Jan-2016

40 views

Category:

Documents


0 download

DESCRIPTION

Systems Analysis & Design Methods. VIII More OOD issues: Patterns & Testing. Books/links:. Design Patterns Gamma, Helm, Johnson, Vlissides (GOF). Contents. Design Patterns What are design patterns ? Why learn patterns ? Reducing the impact of change Some patterns See next slide - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Systems Analysis & Design Methods

Systems Analysis & Systems Analysis & Design Methods Design Methods

VIII More OOD issues:VIII More OOD issues:

Patterns & TestingPatterns & Testing

Page 2: Systems Analysis & Design Methods

2More OOD issues: Patterns & Testing

Books/links:Books/links:

Design PatternsDesign Patterns Gamma, Helm, Johnson, Vlissides (GOF)Gamma, Helm, Johnson, Vlissides (GOF)

Page 3: Systems Analysis & Design Methods

3More OOD issues: Patterns & Testing

ContentsContents

Design PatternsDesign Patterns What are design patterns ?What are design patterns ? Why learn patterns ?Why learn patterns ? Reducing the impact of changeReducing the impact of change Some patternsSome patterns

See next slideSee next slide Automatic Testing anAutomatic Testing an example example

Page 4: Systems Analysis & Design Methods

4More OOD issues: Patterns & Testing

Some design patternsSome design patterns

CreationalCreational Factory MethodFactory Method SingletonSingleton

StructuralStructural Composite Composite FaçadeFaçade

BehavioralBehavioral CommandCommand StateState (covered here) (covered here) TemplateTemplate (covered here) (covered here)

A detailed coverage of patterns will be A detailed coverage of patterns will be given by Patrick Fox in the 3d yeargiven by Patrick Fox in the 3d year

Page 5: Systems Analysis & Design Methods

5More OOD issues: Patterns & Testing

What are design patterns What are design patterns ??

=Standard solutions for standard =Standard solutions for standard problems.problems.

On ‘design’ level: reusable design, not On ‘design’ level: reusable design, not reusable code.reusable code.

It is about slightly bigger designs than It is about slightly bigger designs than described in OO first rules & OOD described in OO first rules & OOD principles.principles.

‘‘design patterns’ have gained attention design patterns’ have gained attention because of the book by the ‘gang of 4’ because of the book by the ‘gang of 4’ GOF (see slide 2)GOF (see slide 2)

Page 6: Systems Analysis & Design Methods

6More OOD issues: Patterns & Testing

Why learn patterns ?Why learn patterns ? Many problems about software modification Many problems about software modification

have a lot in common . They have to do with a have a lot in common . They have to do with a change that has an impact on the entire change that has an impact on the entire system, a change that is simply too big. Design system, a change that is simply too big. Design patterns can help you avoid these problems.patterns can help you avoid these problems.

If you already know some patterns, you loose If you already know some patterns, you loose less time looking for a solution.less time looking for a solution.

A lot of patterns have been discovered a long A lot of patterns have been discovered a long time ago by many developers independent of time ago by many developers independent of each other. But by giving it a single name, each other. But by giving it a single name, communications about patterns are raised to a communications about patterns are raised to a higher level. higher level.

Page 7: Systems Analysis & Design Methods

7More OOD issues: Patterns & Testing

Reducing the impact of Reducing the impact of changechange

ProblemProblem: When creating an object ourselves (with : When creating an object ourselves (with ‘new’), we are dependent of a concrete class. If this ‘new’), we are dependent of a concrete class. If this class has to change (e.g. its name), we might have to class has to change (e.g. its name), we might have to change our code too. (example of change our code too. (example of Dependency Dependency InversionInversion))

pattern/solution: build a pattern/solution: build a Factory MethodFactory Method

Problem:Problem: We already know how to make a new We already know how to make a new method by calling previously developed more method by calling previously developed more elementary methods (see first rules: common code). elementary methods (see first rules: common code). But the other way around also exists : You have to But the other way around also exists : You have to add a method which has the same structure as an add a method which has the same structure as an existing one, but your new method needs other existing one, but your new method needs other elementary methods. How can we use our previous elementary methods. How can we use our previous work (without copy pasting) ? work (without copy pasting) ?

pattern/solution: design a pattern/solution: design a Template Template MethodMethod

Page 8: Systems Analysis & Design Methods

8More OOD issues: Patterns & Testing

Reducing the impact of Reducing the impact of changechange

Problem: Problem: In a previous project we have build classes of In a previous project we have build classes of which we would like to use about 10% . Unfortunately the which we would like to use about 10% . Unfortunately the classes have lots of public methods with lots of parameters classes have lots of public methods with lots of parameters we don’t care about. Also, if we want to use one class we we don’t care about. Also, if we want to use one class we have to know about hundreds of other classes. We are not have to know about hundreds of other classes. We are not allowed to touch the existing classes to improve the designallowed to touch the existing classes to improve the design

pattern/solution: put up a pattern/solution: put up a FaçadeFaçade

Warning: Warning: Don’t be a pattern bigot. Don’t be a pattern bigot. Use a pattern Use a pattern onlyonly when you when you experience the problem it tries to solve experience the problem it tries to solve !!! !!!

Page 9: Systems Analysis & Design Methods

9More OOD issues: Patterns & Testing

State-patternState-pattern A changeable property is represented by A changeable property is represented by

an attribute (see first rules). We cannot an attribute (see first rules). We cannot use a subclass, because an object cannot use a subclass, because an object cannot change its class. But, with a trick, we change its class. But, with a trick, we can exploit the mechanisms of can exploit the mechanisms of subclassing and polymorphism. The trick subclassing and polymorphism. The trick is ‘the state-pattern’.is ‘the state-pattern’.

With an example we show how we can With an example we show how we can avoid if-tests like we always do when avoid if-tests like we always do when using polymorphism.using polymorphism.

Page 10: Systems Analysis & Design Methods

10More OOD issues: Patterns & Testing

State: the problemState: the problem

public double getIncTaxPerc(){public double getIncTaxPerc(){

if ( maritalState == MARRIED )if ( maritalState == MARRIED )

return NORM_PERC - DEDUCTION;return NORM_PERC - DEDUCTION;

elseelse

return NORM_PERC;return NORM_PERC;

} }

Employee

+getMaritalState() : int

-maritalState : int

+getIncTaxPerc() : double

+getPension() : double

Page 11: Systems Analysis & Design Methods

11More OOD issues: Patterns & Testing

State: the problemState: the problem

The problem with the code in de The problem with the code in de previous slide is this:previous slide is this:

If a new marital state is added, If a new marital state is added, (widower), then, all existing similar (widower), then, all existing similar if-tests have to be searched and if-tests have to be searched and changed, thereby altering many changed, thereby altering many classes and maybe forgetting some classes and maybe forgetting some parts.parts.

Page 12: Systems Analysis & Design Methods

12More OOD issues: Patterns & Testing

State: the solutionState: the solution

<<abstract>>MaritalState

MarriedMarriedBachelor

Employee

+get MaritalState() : MaritalState

-maritalState : MaritalState

+getTaxPerc() : double

+getPension() : double

public double getTaxPerc(){public double getTaxPerc(){ return maritalState.getTaxPerc();return maritalState.getTaxPerc();}}

// note: In some cases we have // note: In some cases we have // to pass ‘this’, like in :// to pass ‘this’, like in ://// return burgStand.getBelPerc(return burgStand.getBelPerc(thisthis););

+getTaxPerc() : double

+getPension() : double

+getTaxPerc() : double

+getPension() : double

+getTaxPerc() : double+getTaxPerc() : double

+getPension() : double+getPension() : double

public double getTaxPerc(){public double getTaxPerc(){

return NORM_PERC;return NORM_PERC;

} } public double getTaxPerc(){public double getTaxPerc(){

return NORM_PERC - DEDUCTION;return NORM_PERC - DEDUCTION;

}}

Page 13: Systems Analysis & Design Methods

13More OOD issues: Patterns & Testing

Template Method-Template Method-patternpattern

It often happens that the structure (the It often happens that the structure (the template) of 2 methods is the same is, template) of 2 methods is the same is, but that the more elementary but that the more elementary operations differ. For example, the operations differ. For example, the following code might exist in different following code might exist in different places in a sourcefile: we loop through places in a sourcefile: we loop through al list, thereby using the same if-tests.al list, thereby using the same if-tests.

In the example we show, how we can In the example we show, how we can change the elementary methods change the elementary methods without touching the template-method.without touching the template-method.

Page 14: Systems Analysis & Design Methods

14More OOD issues: Patterns & Testing

Template Method: the Template Method: the problemproblem public void increment(){public void increment(){

for(int i = 0 ; i < list.size(); i++)for(int i = 0 ; i < list.size(); i++)

… …; // increment every element; // increment every element

}}

public void decrement(){public void decrement(){

for(int i = 0 ; i < list.size(); i++)for(int i = 0 ; i < list.size(); i++)

… …; // decrement every element; // decrement every element

}}

public void print(){public void print(){

for(int i = 0 ; i < list.size(); i++)for(int i = 0 ; i < list.size(); i++)

System.out.println( list.get(i) );System.out.println( list.get(i) );

}}

IntegerList

+increment()

-list : List

+decrement()

+print()

Page 15: Systems Analysis & Design Methods

15More OOD issues: Patterns & Testing

Template Method: the Template Method: the problemproblem

The problem with the code in de previous slide The problem with the code in de previous slide is this:is this:

The code is not capable of factoring out the The code is not capable of factoring out the common part, which in this case is: the for-common part, which in this case is: the for-loop .loop .

Every method which runs through the list, Every method which runs through the list, needs to rewrite the for-loop. The problem needs to rewrite the for-loop. The problem deteriorates, if extra conditional code would deteriorates, if extra conditional code would have to be repeated too. have to be repeated too. The structure remains the same,The structure remains the same, The elementary operations differThe elementary operations differ

(increment, decrement,, print, …)(increment, decrement,, print, …)

Page 16: Systems Analysis & Design Methods

16More OOD issues: Patterns & Testing

Template Method: the Template Method: the solutionsolution

public void execute(){public void execute(){

for(int i = 0 ; i < list.size(); i++)for(int i = 0 ; i < list.size(); i++)

operation(i);operation(i);

} }

<<abstract>>

Iteration

DecrementIncrement

+execute()

#operation(int i)

#operation(int i) #operation(int i)

Print

#operation(int i)

protected void operation(int i){protected void operation(int i){

System.out.println(list.get(i)); System.out.println(list.get(i));

}}

IntegerList

+increment()

-list : List

+decrement()

+print()

public void print(){public void print(){

(new Print(list)).execute();(new Print(list)).execute();

}}

-list : List

<<abstract>>

Page 17: Systems Analysis & Design Methods

17More OOD issues: Patterns & Testing

Automatic TestingAutomatic Testingan examplean example

The Class DiagramThe Class Diagram Start writing the test class.Start writing the test class. Repeat until all tests are written and Repeat until all tests are written and

passedpassed Write a test in the test class.Write a test in the test class. Write part of the tested class, enough for Write part of the tested class, enough for

the test class and the tested class to survive the test class and the tested class to survive compilation.compilation.

Write the part of the tested class that makes Write the part of the tested class that makes it pass the testit pass the test

Write another test. Write another test.

Page 18: Systems Analysis & Design Methods

18More OOD issues: Patterns & Testing

Automatic TestingAutomatic Testingan examplean example

Write the test before you write what Write the test before you write what is tested.is tested.

Advantages of automated tests:Advantages of automated tests: Code requirements are clearly specified: Code requirements are clearly specified:

just look at the tests.just look at the tests. Testing whether requirements are met, Testing whether requirements are met,

is easy: just run the tests.is easy: just run the tests. Possible damage, caused by adapting Possible damage, caused by adapting

code, is found quickly: just run the tests.code, is found quickly: just run the tests.

Page 19: Systems Analysis & Design Methods

19More OOD issues: Patterns & Testing

Automatic TestingAutomatic Testingan examplean example

Directory structure:Directory structure: c:\c:\

javaoefjavaoef testtest

Test.java Test.java (serves as abstract superclass (serves as abstract superclass to your own test to your own test

classes)classes)

invoiceAppinvoiceApp Invoice.java Invoice.java (in a minute)(in a minute) InvoiceLine.javaInvoiceLine.java

invoiceAppTestinvoiceAppTest InvoiceAppTest.java InvoiceAppTest.java (concrete testclass)(concrete testclass)

Page 20: Systems Analysis & Design Methods

20More OOD issues: Patterns & Testing

Class Model: Integration Class Model: Integration with ‘test with ‘test envirenvironment’onment’

Page 21: Systems Analysis & Design Methods

21More OOD issues: Patterns & Testing

InvoiceAppTest.javaInvoiceAppTest.javapackage invoiceAppTest;package invoiceAppTest;

import java.util.Date;import java.util.Date;import test.Test;import test.Test;import invoiceApp.*;import invoiceApp.*;

public class InvoiceAppTest public class InvoiceAppTest extends Testextends Test{{

public static void main(String[] args){public static void main(String[] args){ (new InvoiceAppTest()).run();(new InvoiceAppTest()).run(); }}

protected void compareAll(){ protected void compareAll(){ // Tests go here// Tests go here }}}}

Page 22: Systems Analysis & Design Methods

22More OOD issues: Patterns & Testing

Write a test in the test Write a test in the test classclass

// Instead of ‘Tests go here’ we write// Instead of ‘Tests go here’ we write:: // Creation invoice object inv1// Creation invoice object inv1 Invoice inv1;Invoice inv1; inv1 = new Invoice("Jef","Peters",inv1 = new Invoice("Jef","Peters", "BE-123-456-789", new Date());"BE-123-456-789", new Date()); inv1.addInvoiceLine("Red Paint",50.0,3);inv1.addInvoiceLine("Red Paint",50.0,3); inv1.addInvoiceLine("Blew Paint",45.0,2);inv1.addInvoiceLine("Blew Paint",45.0,2); inv1.addInvoiceLine("Brush Medium",79.95,5);inv1.addInvoiceLine("Brush Medium",79.95,5); // Creation invoice object inv2: LIKE ABOVE// Creation invoice object inv2: LIKE ABOVE

// test inv1:// test inv1: compareAndReportcompareAndReport("inv1",inv1.getTotPrice()+"", "639.75" ); ("inv1",inv1.getTotPrice()+"", "639.75" );

// test inv2:// test inv2: compareAndReportcompareAndReport("inv2",inv2.getTotPrice()+"", "586.0" );("inv2",inv2.getTotPrice()+"", "586.0" );

Inherited from test.Test

Page 23: Systems Analysis & Design Methods

23More OOD issues: Patterns & Testing

Just enough to compile: Just enough to compile: Invoice.javaInvoice.java// Contains just enough code for a successful compile // Contains just enough code for a successful compile

// All tests fail ofcourse:// All tests fail ofcourse:package invoiceApp;package invoiceApp;

import java.util.ArrayList;import java.util.ArrayList;import java.util.Date;import java.util.Date;

public class Invoice{public class Invoice{

public Invoice (String lastName,public Invoice (String lastName, String firstName,String firstName, String TAX,String TAX, Date date){ Date date){ } } public void addInvoiceLine(String desc,public void addInvoiceLine(String desc, double price,double price, int qty){int qty){ } } public double getTotPrice(){public double getTotPrice(){ return 0.0;return 0.0; }}}}

Page 24: Systems Analysis & Design Methods

24More OOD issues: Patterns & Testing

CompilationCompilation

C:\javaoef>C:\javaoef>javac invoiceAppTest\InvoiceAppTest.javajavac invoiceAppTest\InvoiceAppTest.java

The other classes are also compiled because The other classes are also compiled because they arethey are

referred to in the code.referred to in the code.

Page 25: Systems Analysis & Design Methods

25More OOD issues: Patterns & Testing

Running the testRunning the test

C:\javaoef>C:\javaoef>java invoiceAppTest.InvoiceAppTestjava invoiceAppTest.InvoiceAppTest

ERROR! fac1 | calculated=0.0, expected=639.75ERROR! fac1 | calculated=0.0, expected=639.75

ERROR! fac2 | calculated=0.0, expected=586ERROR! fac2 | calculated=0.0, expected=586

Total error count (errors/tests): 2/2Total error count (errors/tests): 2/2

Page 26: Systems Analysis & Design Methods

26More OOD issues: Patterns & Testing

Make it pass the test: Make it pass the test: Invoice.javaInvoice.javapackage invoiceApp;package invoiceApp;

import java.util.ArrayList;import java.util.ArrayList;import java.util.Date;import java.util.Date;

public class Invoice{public class Invoice{

public Invoice (String lastName,public Invoice (String lastName, String firstName,String firstName, String TAX,String TAX, Date date){ Date date){ } }

private ArrayList lines = new ArrayList();private ArrayList lines = new ArrayList(); public void addInvoiceLine(String desc,public void addInvoiceLine(String desc, double price,double price, int qty){int qty){ InvoiceLine line = new InvoiceLine(desc,price,qty); InvoiceLine line = new InvoiceLine(desc,price,qty);

lines.add(line); lines.add(line); } } public double getTotPrice(){public double getTotPrice(){ double totPrice = 0.0;double totPrice = 0.0; for (int i=0; i < lines.size(); i++){for (int i=0; i < lines.size(); i++){ InvoiceLine line;InvoiceLine line; line = (InvoiceLine) lines.get(i);line = (InvoiceLine) lines.get(i); totPrice += line.getInvoiceLinePrice();totPrice += line.getInvoiceLinePrice(); } } return totPrice;return totPrice; }}}}

Page 27: Systems Analysis & Design Methods

27More OOD issues: Patterns & Testing

Make it pass the test: Make it pass the test: InvoiceLine.javaInvoiceLine.java

package invoiceApp; package invoiceApp;

public class InvoiceLine{public class InvoiceLine{

public InvoiceLine(String desc,double price, int qty){public InvoiceLine(String desc,double price, int qty){ this.price = price;this.price = price; this.qty = qty;this.qty = qty; }} private double price;private double price; private int qty;private int qty; public double getInvoiceLinePrice(){public double getInvoiceLinePrice(){ return price * qty;return price * qty; } } }}

Page 28: Systems Analysis & Design Methods

28More OOD issues: Patterns & Testing

Compilation and test-runCompilation and test-run

C:\javaoef>C:\javaoef>javac invoiceAppTest\javac invoiceAppTest\InvoiceAppTest.javaInvoiceAppTest.java

C:\javaoef>C:\javaoef>java invoiceAppTest.InvoiceAppTestjava invoiceAppTest.InvoiceAppTest

Everything works fine (2 tests passed)Everything works fine (2 tests passed)