Teaching Java Framework Design Using Classic Problems

55
Teaching Java Framework Design Using Classic Problems H. Conrad Cunningham H. Conrad Cunningham 1 Yi Liu Yi Liu 2 Cuihua Zhang Cuihua Zhang 3 1 University of Mississippi University of Mississippi 2 2 South Dakota State University South Dakota State University 3 Northeast Lakeview College Northeast Lakeview College

description

Teaching Java Framework Design Using Classic Problems. H. Conrad Cunningham 1 Yi Liu 2 Cuihua Zhang 3 1 University of Mississippi 2 South Dakota State University 3 Northeast Lakeview College. Outline. Motivation Software families Foundational concepts Framework construction - PowerPoint PPT Presentation

Transcript of Teaching Java Framework Design Using Classic Problems

Page 1: Teaching Java Framework Design Using Classic Problems

Teaching Java Framework Design Using Classic Problems

H. Conrad Cunningham H. Conrad Cunningham 11 Yi Liu Yi Liu 22 Cuihua Zhang Cuihua Zhang 33

11 University of Mississippi University of Mississippi2 2 South Dakota State UniversitySouth Dakota State University33 Northeast Lakeview College Northeast Lakeview College

Page 2: Teaching Java Framework Design Using Classic Problems

22

OutlineOutline

MotivationMotivation Software familiesSoftware families Foundational conceptsFoundational concepts Framework constructionFramework construction Divide and conquer case studyDivide and conquer case study ObservationsObservations Framework generalization using function Framework generalization using function

generalizationgeneralization Binary tree traversal case studyBinary tree traversal case study ConclusionsConclusions

Page 3: Teaching Java Framework Design Using Classic Problems

33

Technical MotivationTechnical Motivation

Software Software becoming more pervasivebecoming more pervasive increasing in size and complexityincreasing in size and complexity expected to provide product flexibilityexpected to provide product flexibility

Therefore, need to increase productivity, Therefore, need to increase productivity, manage complexity, and provide manage complexity, and provide flexibility to systems builders flexibility to systems builders

Page 4: Teaching Java Framework Design Using Classic Problems

44

Competitive MotivationCompetitive Motivation

““Heads down” programming expertise Heads down” programming expertise has become commodity skill available has become commodity skill available globally globally

Therefore, our students need toTherefore, our students need to become skilled domain analystsbecome skilled domain analysts learn to adapt software to local needslearn to adapt software to local needs master higher level concepts and skillsmaster higher level concepts and skills

Page 5: Teaching Java Framework Design Using Classic Problems

55

One Response: One Response: Focus on Software FamiliesFocus on Software Families

Software family is set of programsSoftware family is set of programs Sharing many common propertiesSharing many common properties Worthwhile to study as a group before each Worthwhile to study as a group before each

individuallyindividually Known as software frameworks or product linesKnown as software frameworks or product lines

David ParnasDavid Parnas::““If you are developing a family of programs, you If you are developing a family of programs, you must do that consciously, or you will incur must do that consciously, or you will incur unnecessary long-term costs.”unnecessary long-term costs.”

Page 6: Teaching Java Framework Design Using Classic Problems

66

How Much Progress?How Much Progress?

In 1976, Parnas published the seminal article In 1976, Parnas published the seminal article “On the Design and Development of Program “On the Design and Development of Program Families.”Families.”

In 2001, Parnas wrote:In 2001, Parnas wrote:““Although there is now growing … interest and Although there is now growing … interest and some evidence of … success in applying the some evidence of … success in applying the idea, the majority of industrial programmers idea, the majority of industrial programmers seem to ignore it in their rush to produce code.”seem to ignore it in their rush to produce code.”

Page 7: Teaching Java Framework Design Using Classic Problems

77

Our ViewpointOur Viewpoint

Students shouldStudents should:: Learn concepts and methods for designing Learn concepts and methods for designing

software familiessoftware families Learn technologies for designing and Learn technologies for designing and

implementing software family as frameworkimplementing software family as framework

Teachers can:Teachers can: Use familiar problems initially to introduce the Use familiar problems initially to introduce the

new concepts and technologiesnew concepts and technologies

Page 8: Teaching Java Framework Design Using Classic Problems

88

Foundational Concepts Foundational Concepts

Classic concepts (Parnas)Classic concepts (Parnas)– information hiding modulesinformation hiding modules– abstract interfacesabstract interfaces

Object-oriented programmingObject-oriented programming– inheritanceinheritance– polymorphismpolymorphism

Design patternsDesign patterns

Page 9: Teaching Java Framework Design Using Classic Problems

99

Information-Hiding ModulesInformation-Hiding Modules

Module Module Work assignment given to a programmer or group of Work assignment given to a programmer or group of

programmersprogrammers Good characteristics: independent development, Good characteristics: independent development,

comprehensible, changeablecomprehensible, changeable

Information hidingInformation hiding Design modules around assumptions likely to changeDesign modules around assumptions likely to change Hide a design decision within a moduleHide a design decision within a module

– as its as its secretsecret

Page 10: Teaching Java Framework Design Using Classic Problems

1010

Abstract InterfacesAbstract Interfaces

InterfaceInterface Set of assumptions programmer must make Set of assumptions programmer must make

about another module to demonstrate about another module to demonstrate correctness of his modulecorrectness of his module

– not just syntax, also semanticsnot just syntax, also semantics

Abstract interfaceAbstract interface Module interface that does not change when Module interface that does not change when

one module implementation is substituted for one module implementation is substituted for anotheranother

Page 11: Teaching Java Framework Design Using Classic Problems

1111

Design PatternsDesign Patterns

Well-established solutions to Well-established solutions to recurring design problemsrecurring design problems

E.g. Template Method, Strategy, E.g. Template Method, Strategy, Composite, Visitor, SingletonComposite, Visitor, Singleton

Page 12: Teaching Java Framework Design Using Classic Problems

1212

Software FrameworkSoftware Framework

Generic application allowing creation of Generic application allowing creation of members of family of related programsmembers of family of related programs

Reusable design expressed as set of abstract Reusable design expressed as set of abstract classes and way they collaborateclasses and way they collaborate

Common and variable aspects known as Common and variable aspects known as frozen spotsfrozen spots and and hot spotshot spots

FrameworkFramework

library

User-supplied code(application specific)

Hot spots

Frozen spots

Page 13: Teaching Java Framework Design Using Classic Problems

1313

Hot Spot SubsystemHot Spot Subsystem

Template methodTemplate method defines a common behavior defines a common behavior for familyfor family– part of frozen spot implementationpart of frozen spot implementation

Template method calls Template method calls hook methodshook methods to invoke to invoke behaviors specific to family memberbehaviors specific to family member– hook methods formhook methods form hot spot subsystem hot spot subsystem

– set of hook methods form abstract interface to set of hook methods form abstract interface to information hiding moduleinformation hiding module

Page 14: Teaching Java Framework Design Using Classic Problems

1414

Framework Construction Framework Construction PrinciplesPrinciples

UnificationUnification

– Use Use inheritanceinheritance to implement hot spot to implement hot spot subsystem subsystem

SeparationSeparation

– Use Use delegationdelegation to implement hot spot to implement hot spot subsystemsubsystem

Page 15: Teaching Java Framework Design Using Classic Problems

1515

Unification PrincipleUnification Principle

Template Method pattern Template Method pattern

AbstractClass

TemplateMethods

HookMethods

ConcreteClass

HookMethods

Page 16: Teaching Java Framework Design Using Classic Problems

1616

Separation PrincipleSeparation Principle

Strategy patternStrategy pattern

Strategy

HookMethods

ConcreteStrategyB

HookMethods

ConcreteStrategyC

HookMethods

ConcreteStrategyA

HookMethods

Context

TemplateMethods

strategy

Page 17: Teaching Java Framework Design Using Classic Problems

1717

Example:Example:Divide and Conquer AlgorithmsDivide and Conquer Algorithms

Divide original problem into Divide original problem into subproblems of same typesubproblems of same type

Solve each subproblem independentlySolve each subproblem independently

Combine subproblem solutions into Combine subproblem solutions into solution for original problemsolution for original problem

What are some examples?What are some examples?

Page 18: Teaching Java Framework Design Using Classic Problems

1818

Well-Known ExamplesWell-Known Examples

MergesortMergesort QuicksortQuicksort HeapifyHeapify Binary searchBinary search Fast matrix multiplicationFast matrix multiplication Fast Fourier Transform (FFT)Fast Fourier Transform (FFT)

Page 19: Teaching Java Framework Design Using Classic Problems

1919

Example: MergesortExample: Mergesort

1 12 10 6

1 12

10 6

1 12 10 6

1 12

6 10

1 6 10 12

Page 20: Teaching Java Framework Design Using Classic Problems

2020

Divide and Conquer PseudocodeDivide and Conquer Pseudocode

function function solvesolve(p)(p){ if { if isSimpleisSimple(p)(p) return return simplySolvesimplySolve(p);(p);elseelse{{

Problem [] sp = Problem [] sp = decomposedecompose(p);(p); for (i = 0; i<sp.length; i = i+1)for (i = 0; i<sp.length; i = i+1)

sol[i] = sol[i] = solvesolve(sp[i]);(sp[i]); return return combinecombine (sol); (sol); }}}}

Page 21: Teaching Java Framework Design Using Classic Problems

2121

Divide & Conquer FunctionsDivide & Conquer Functions

template method: template method: – solvesolve()()

hook methods: hook methods: – isSimpleisSimple()()– simplySolvesimplySolve()()– decomposedecompose()()– combinecombine()()

other: other: problemproblem and and solutionsolution descriptions descriptions

Page 22: Teaching Java Framework Design Using Classic Problems

2222

Framework: Framework: Template Method PatternTemplate Method Pattern

DivConqTemplate

final void solve()abstract isSimple()abstract simplySolve()abstract decompose()abstract combine()

Divide and Conquer

MergeSort

isSimple()simplySolve()decompose()combine()

BinarySearch

isSimple()simplySolve()decompose()combine()

QuickSort

isSimple()simplySolve()decompose()combine()

Page 23: Teaching Java Framework Design Using Classic Problems

2323

Template Method ClassTemplate Method Class

abstract public class DivConqTemplateabstract public class DivConqTemplate{ final public { final public SolutionSolution solvesolve ((ProblemProblem p) p) { { ProblemProblem[] pp; [] pp; if (isSimple(p)) { return if (isSimple(p)) { return simplySolvesimplySolve(p); }(p); } else { pp = else { pp = decomposedecompose(p); }(p); } Solution[] ss = new Solution[] ss = new SolutionSolution[pp.length];[pp.length]; for(int i=0; i < pp.length; i++) for(int i=0; i < pp.length; i++) { ss[i] = { ss[i] = solvesolve(pp[i]); }(pp[i]); } return return combinecombine(p,ss);(p,ss); }} abstract protected boolean abstract protected boolean isSimpleisSimple ( (ProblemProblem p); p); abstract protected abstract protected Solution simplySolveSolution simplySolve ( (ProblemProblem p); p); abstract protected abstract protected ProblemProblem[] [] decomposedecompose ( (ProblemProblem p); p); abstract protected abstract protected SolutionSolution combinecombine ((ProblemProblem p, p, SolutionSolution[] ss);[] ss);}}

Page 24: Teaching Java Framework Design Using Classic Problems

2424

Framework Application: Framework Application: QuicksortQuicksort

Divide and conquer task: sort a sequence in placeDivide and conquer task: sort a sequence in place Mapping problem into divide and conquer Mapping problem into divide and conquer

frameworkframework– decomposedecompose: partition into two segments about a : partition into two segments about a

pivot value (rearranges values in array)pivot value (rearranges values in array)– recursively sort each segment until just one recursively sort each segment until just one

element (element (isSimpleisSimple and and simplySolvesimplySolve))– combinecombine: : values already in needed locationvalues already in needed location

Describing the problem and solutionDescribing the problem and solution– identify sequence of valuesidentify sequence of values– identify beginning and ending elements of segmentidentify beginning and ending elements of segment

Page 25: Teaching Java Framework Design Using Classic Problems

2525

Problem and Solution Problem and Solution DescriptionDescription

Simplifying assumption: sort integer arraysSimplifying assumption: sort integer arrays ProblemProblem description for sort description for sort

– overall arrayoverall array– beginning and ending indices of segmentbeginning and ending indices of segment

SolutionSolution description for sort description for sort– same as same as ProblemProblem description description– except array values rearranged in placeexcept array values rearranged in place

QuickSortDescQuickSortDesc to represent both to represent both

Page 26: Teaching Java Framework Design Using Classic Problems

2626

QuickSortDesc ClassQuickSortDesc Class

public class QuickSortDesc public class QuickSortDesc implements Problem, Solutionimplements Problem, Solution{ public QuickSortDesc{ public QuickSortDesc (int[] arr, int first, int last) (int[] arr, int first, int last) { this.arr = arr; { this.arr = arr; this.first = first; this.last = last;this.first = first; this.last = last; }} public int getFirst () { return first; }public int getFirst () { return first; } public int getLast () { return last; }public int getLast () { return last; } public int[] getArr () { return arr; }public int[] getArr () { return arr; } private int[] arr;private int[] arr; private int first, last;private int first, last;}}

Page 27: Teaching Java Framework Design Using Classic Problems

2727

Quicksort Subclass (1 of 3)Quicksort Subclass (1 of 3)

public class QuickSort extends DivConqTemplatepublic class QuickSort extends DivConqTemplate

{ protected boolean { protected boolean isSimpleisSimple (Problem p) (Problem p)

{ return ({ return (

((QuickSortDesc)p).getFirst()((QuickSortDesc)p).getFirst()

>=>=

((QuickSortDesc)p).getLast() );((QuickSortDesc)p).getLast() );

}}

protected Solution protected Solution simplySolve simplySolve (Problem p)(Problem p)

{ return (Solution) p ; }{ return (Solution) p ; }

Page 28: Teaching Java Framework Design Using Classic Problems

2828

Quicksort Subclass (2 of 3)Quicksort Subclass (2 of 3)

protected Problem[] protected Problem[] decomposedecompose (Problem p) (Problem p) { int first = ((QuickSortDesc)p).getFirst();{ int first = ((QuickSortDesc)p).getFirst(); int last = ((QuickSortDesc)p).getLast();int last = ((QuickSortDesc)p).getLast(); int[] a = ((QuickSortDesc)p).getArr ();int[] a = ((QuickSortDesc)p).getArr (); int x = a[first]; // pivot valueint x = a[first]; // pivot value int sp = first;int sp = first; for (int i = first + 1; i <= last; i++)for (int i = first + 1; i <= last; i++) { if (a[i] < x) { swap (a, ++sp, i); } }{ if (a[i] < x) { swap (a, ++sp, i); } } swap (a, first, sp);swap (a, first, sp); Problem[] ps = new QuickSortDesc[2];Problem[] ps = new QuickSortDesc[2]; ps[0] = new QuickSortDesc(a,first,sp-1);ps[0] = new QuickSortDesc(a,first,sp-1); ps[1] = new QuickSortDesc(a,sp+1,last);ps[1] = new QuickSortDesc(a,sp+1,last); return ps;return ps; } }

Page 29: Teaching Java Framework Design Using Classic Problems

2929

Quicksort Subclass (3 of 3)Quicksort Subclass (3 of 3)

protected Solution protected Solution combinecombine

(Problem p, Solution[] ss)(Problem p, Solution[] ss)

{ return (Solution) p; } // should make sure adj{ return (Solution) p; } // should make sure adj

private void swap (int [] a, int first, int last)private void swap (int [] a, int first, int last)

{ int temp = a[first];{ int temp = a[first];

a[first] = a[last];a[first] = a[last];

a[last] = temp;a[last] = temp;

}}

} }

Page 30: Teaching Java Framework Design Using Classic Problems

3030

To Build a FrameworkTo Build a Framework

Represent Represent common aspectscommon aspects as as abstract abstract classesclasses and and concrete template methodsconcrete template methods

Represent Represent variable aspectsvariable aspects as as abstract abstract hook methodshook methods and some and some concrete hook concrete hook methodsmethods in hot spot subsystems in hot spot subsystems

Organize using unification or Organize using unification or separation principleseparation principle

Page 31: Teaching Java Framework Design Using Classic Problems

3131

To Use a FrameworkTo Use a Framework

Implement concrete hook methods Implement concrete hook methods

Plug subsystems into hot spotsPlug subsystems into hot spots

Page 32: Teaching Java Framework Design Using Classic Problems

3232

Educational ObservationsEducational Observations

Students should learn to design program familiesStudents should learn to design program families Students should be explicitly taught appropriate Students should be explicitly taught appropriate

design and programming techniquesdesign and programming techniques Frameworks are understandable by students Frameworks are understandable by students

familiar with OOPfamiliar with OOP Divide and Conquer algorithmic strategy provides Divide and Conquer algorithmic strategy provides

a familiar, understandable environment for a familiar, understandable environment for learninglearning

Other exercises are needed to teach students to Other exercises are needed to teach students to identify and design appropriate hot spotsidentify and design appropriate hot spots

Page 33: Teaching Java Framework Design Using Classic Problems

3333

Framework GeneralizationFramework Generalization

Nontrivial to identify needed hot spot Nontrivial to identify needed hot spot abstractionsabstractions

Difficult to specify hot spot behaviorsDifficult to specify hot spot behaviors

Need systematic generalization methodology Need systematic generalization methodology ExploreExplore function generalization function generalization

– incrementally generalize functional structure of incrementally generalize functional structure of specification to produce general applicationspecification to produce general application

Page 34: Teaching Java Framework Design Using Classic Problems

3434

Binary Tree TraversalBinary Tree Traversal

procedure preorder(t)procedure preorder(t){ if t null, then return;{ if t null, then return; perform visit action for root of tree t;perform visit action for root of tree t; preorder (left subtree of t);preorder (left subtree of t); preorder (right subtree of t);preorder (right subtree of t);}}

21

18

3 20

50

30

1

Preorder 21 18 3 1 20 50 30

Page 35: Teaching Java Framework Design Using Classic Problems

3535

Function GeneralizationFunction Generalization

Create a prototype of one family member Create a prototype of one family member Define scope of familyDefine scope of family Identify frozen spots and hot spotsIdentify frozen spots and hot spots Analyze and design each hot spot systemAnalyze and design each hot spot system

– generalize program for hot spotgeneralize program for hot spot

– transform simple function to template method with transform simple function to template method with hook callshook calls

Page 36: Teaching Java Framework Design Using Classic Problems

3636

Composite Pattern for StructureComposite Pattern for Structure

1

*

BinTree

abstract getValue( )abstract getLeft( )abstract getright( )abstract setValue( )abstract setLeft( )anstract setRight( )

NodeNil

Component

Leaf

Composite

Page 37: Teaching Java Framework Design Using Classic Problems

3737

Binary Tree Component Base Class:Binary Tree Component Base Class:Preorder TraversalPreorder Traversal

abstract public class BinTree abstract public class BinTree

{ public void setValue(Object v) { } // mutators{ public void setValue(Object v) { } // mutators

public void setLeft(BinTree l) { } // defaultpublic void setLeft(BinTree l) { } // default

public void setRight(BinTree r){ }public void setRight(BinTree r){ }

abstract public void preorder();abstract public void preorder();

public Object getValue() { return null; } // accessorspublic Object getValue() { return null; } // accessors

public BinTree getLeft() { return null; } // defaultpublic BinTree getLeft() { return null; } // default

public BinTree getRight(){ return null; } public BinTree getRight(){ return null; }

}}

Page 38: Teaching Java Framework Design Using Classic Problems

3838

Binary Tree Composite Node Class:Binary Tree Composite Node Class:Preorder TraversalPreorder Traversal

public classpublic class Node extends BinTreeNode extends BinTree{ public Node(Object v, BinTree l, BinTree r){ public Node(Object v, BinTree l, BinTree r) { value = v; left = l; right = r; }{ value = v; left = l; right = r; } public void setValue(Object v) { value = v; }public void setValue(Object v) { value = v; } public void setLeft(BinTree l) { left = l; }public void setLeft(BinTree l) { left = l; } public void setRight(BinTree r) { right = r; }public void setRight(BinTree r) { right = r; } public void preorder() // traversalpublic void preorder() // traversal { System.out.println("Visit node with value “ + value);{ System.out.println("Visit node with value “ + value); left.preorder(); right.preorderleft.preorder(); right.preorder();(); }} public Object getValue() { return value; }public Object getValue() { return value; } public BinTree getLeft() { return left; }public BinTree getLeft() { return left; } public BinTree getRight() { return right; } public BinTree getRight() { return right; } private Object value; private Object value; private BinTree left, right;private BinTree left, right;}}

Page 39: Teaching Java Framework Design Using Classic Problems

3939

Binary Tree Leaf Node Class:Binary Tree Leaf Node Class:Preorder TraversalPreorder Traversalpublic class Nil extends BinTreepublic class Nil extends BinTree{ private Nil(){ } // require use of getNil(){ private Nil(){ } // require use of getNil() public void preorder(){ }; // traversalpublic void preorder(){ }; // traversal static public void getNil() // Singletonstatic public void getNil() // Singleton { return theNil; }{ return theNil; } static private BinTree theNil = new Nil();static private BinTree theNil = new Nil();}}

Page 40: Teaching Java Framework Design Using Classic Problems

4040

Framework ScopeFramework Scope

Standard kinds of depth-first traversalsStandard kinds of depth-first traversals Flexible visit actions that are functions of Flexible visit actions that are functions of

accumulated state along traversalaccumulated state along traversal Other traversals orders (e.g. level by level)Other traversals orders (e.g. level by level) Binary trees, but not multiway trees or graphs Binary trees, but not multiway trees or graphs

What are the frozen spots and the hot spots?What are the frozen spots and the hot spots?

Page 41: Teaching Java Framework Design Using Classic Problems

4141

Frozen SpotsFrozen Spots

1.1. Structure of tree not redefined by clientsStructure of tree not redefined by clients

2.2. Traversal accesses every node once Traversal accesses every node once (unless stopped early) (unless stopped early)

3.3. Traversal performs one or more visit Traversal performs one or more visit actions on access to node of treeactions on access to node of tree

Represented by a traversal methodRepresented by a traversal method

Page 42: Teaching Java Framework Design Using Classic Problems

4242

Hot SpotsHot Spots

1.1. Variability in the visit operation’s actionVariability in the visit operation’s action2.2. Variability in ordering of visit action with Variability in ordering of visit action with

respect to subtree visitsrespect to subtree visits3.3. Variability in tree navigation technique (not Variability in tree navigation technique (not

just left-to-right, depth first)just left-to-right, depth first)

Represented as additional functions, types, and Represented as additional functions, types, and class definitions to traversal functionclass definitions to traversal function

Page 43: Teaching Java Framework Design Using Classic Problems

4343

Hot Spot #1:Hot Spot #1:Generalizing the Visit ActionGeneralizing the Visit Action

Represent visit action by state-updating Strategy Represent visit action by state-updating Strategy object passed into traversal functionobject passed into traversal function

Accumulate state along traversal pathAccumulate state along traversal path

abstract public class BinTree abstract public class BinTree

{ ...{ ...

abstract public Object preorder abstract public Object preorder

(Object ts, PreorderStrategy v);(Object ts, PreorderStrategy v);

......

}}

public interface PreorderStrategypublic interface PreorderStrategy

{ abstract public Object visitPre(Object ts, BinTree t); }{ abstract public Object visitPre(Object ts, BinTree t); }

Page 44: Teaching Java Framework Design Using Classic Problems

4444

Hot Spot #1:Hot Spot #1:Generalizing the Visit ActionGeneralizing the Visit Action

public class Node extends BinTreepublic class Node extends BinTree{ ...{ ... public Object preorder (Object ts, PreorderStrategy v)public Object preorder (Object ts, PreorderStrategy v) { ts = v.visitPre(ts, this); ts = left.preorder(ts, v);{ ts = v.visitPre(ts, this); ts = left.preorder(ts, v); ts = right.preorder(ts, v); return ts;ts = right.preorder(ts, v); return ts; }} ......}}public class Nil extends BinTreepublic class Nil extends BinTree{ ...{ ... public Object preorderpublic Object preorder (Object ts, PreorderStrategy v)(Object ts, PreorderStrategy v) { return ts; }{ return ts; } ......}}

Page 45: Teaching Java Framework Design Using Classic Problems

4545

Hot Spot #2:Hot Spot #2:Generalizing the Visit OrderGeneralizing the Visit Order

Allow visit actions at first arrival (left), between Allow visit actions at first arrival (left), between subtree traversals (bottom), and before final departure subtree traversals (bottom), and before final departure (right) -- Euler tree traversal(right) -- Euler tree traversal

abstract public class BinTree abstract public class BinTree { ...{ ... abstract public Object traverseabstract public Object traverse (Object ts, EulerStrategy v) ;(Object ts, EulerStrategy v) ; ......}}public interface EulerStrategypublic interface EulerStrategy{ abstract public Object visitLeft(Object ts,BinTree t);{ abstract public Object visitLeft(Object ts,BinTree t); abstract public Object visitBottom(Object ts,BinTree t);abstract public Object visitBottom(Object ts,BinTree t); abstract public Object visitRight(Object ts,BinTree t);abstract public Object visitRight(Object ts,BinTree t); abstract public Object visitNil(Object ts,BinTree t);abstract public Object visitNil(Object ts,BinTree t);}}

Page 46: Teaching Java Framework Design Using Classic Problems

4646

Hot Spot #2:Hot Spot #2:Generalizing the Visit OrderGeneralizing the Visit Order

public class Node extends BinTreepublic class Node extends BinTree{ ...{ ... public Object traverse (Object ts, EulerStrategy v)public Object traverse (Object ts, EulerStrategy v) { ts = v.visitLeft(ts,this); // arrival from above{ ts = v.visitLeft(ts,this); // arrival from above ts = left.traverse(ts,v);ts = left.traverse(ts,v); ts = v.visitBottom(ts,this); // return from belowts = v.visitBottom(ts,this); // return from below ts = right.traverse(ts,v);ts = right.traverse(ts,v); ts = v.visitRight(ts,this); // completionts = v.visitRight(ts,this); // completion return ts;return ts; } ...} ...}}public class Nil extends BinTreepublic class Nil extends BinTree{ { ...... public Object traverse (Object ts, EulerStrategy v) public Object traverse (Object ts, EulerStrategy v) { return v.visitNil(ts,this); } ...{ return v.visitNil(ts,this); } ...}}

Page 47: Teaching Java Framework Design Using Classic Problems

4747

Hot Spot #3:Hot Spot #3:Generalizing the Tree NavigationGeneralizing the Tree Navigation

Visitor patternVisitor pattern

MappingVisitor

BinTreeVisitorTest

Client Visitor

Concrete Visitor

Concrete Visitor

BreadthFirstVisitorEulerTourVisitor

Concrete Element

BinTree (Element)

abstract accept( )abstract getValue( )abstract getLeft( )abstract getRight( )abstract setValue( )abstract setLeft( )abstract setRight( )

BinTreeVisitor

abstract visit( )

<<abstract Interface>>

uses

NodeNil

Page 48: Teaching Java Framework Design Using Classic Problems

4848

Hot Spot #3:Hot Spot #3:Generalizing the Tree NavigationGeneralizing the Tree Navigation

abstract public class BinTree abstract public class BinTree { ...{ ... abstract public void accept (BinTreeVisitor v); abstract public void accept (BinTreeVisitor v); // accept Visitor v// accept Visitor v // e.g., v.visit(this)// e.g., v.visit(this) ......}}

public interface BinTreeVisitorpublic interface BinTreeVisitor{ abstract void visit (Node t); // overloaded{ abstract void visit (Node t); // overloaded abstract void visit (Nil t); // method nameabstract void visit (Nil t); // method name}}

Page 49: Teaching Java Framework Design Using Classic Problems

4949

Hot Spot #3:Hot Spot #3:Euler Tour Traversal as Special CaseEuler Tour Traversal as Special Case

public class EulerTourVisitor implements BinTreeVisitorpublic class EulerTourVisitor implements BinTreeVisitor{ public EulerTourVisitor(EulerStrategy es, Object ts){ public EulerTourVisitor(EulerStrategy es, Object ts) { this.es = es; this.ts = ts; }{ this.es = es; this.ts = ts; } public void setVisitStrategy(EulerStrategy es) public void setVisitStrategy(EulerStrategy es) { this.es = es; }{ this.es = es; } public void setResult(Object r) { ts = r; }public void setResult(Object r) { ts = r; } public void visit(Node t) // Visitor hookspublic void visit(Node t) // Visitor hooks { ts = es.visitLeft(ts,t); // arrival from above{ ts = es.visitLeft(ts,t); // arrival from above t.getLeft().accept(this);t.getLeft().accept(this); ts = es.visitBottom(ts,t); // return from belowts = es.visitBottom(ts,t); // return from below t.getRight().accept(this);t.getRight().accept(this); ts = es.visitRight(ts,t); // completionts = es.visitRight(ts,t); // completion }} public void visit(Nil t) { ts = es.visitNil(ts,t); }public void visit(Nil t) { ts = es.visitNil(ts,t); } public Object getResult(){ return ts; } // accessorpublic Object getResult(){ return ts; } // accessor private EulerStrategy es; // state changing opsprivate EulerStrategy es; // state changing ops private Object ts; // traversal stateprivate Object ts; // traversal state}}

Page 50: Teaching Java Framework Design Using Classic Problems

5050

Generalization RecapGeneralization Recap

Used Used function generalization function generalization to construct to construct framework systematically and incrementallyframework systematically and incrementally

Produced an executable program prototype Produced an executable program prototype at each transformationat each transformation

Defined appropriate hooks (hot spot Defined appropriate hooks (hot spot abstractions) at each stepabstractions) at each step

Constructed general binary tree traversal Constructed general binary tree traversal program with better understanding of program with better understanding of supported hot spot behaviorssupported hot spot behaviors

Page 51: Teaching Java Framework Design Using Classic Problems

5151

Educational ObservationsEducational Observations

Design of software families not easyDesign of software families not easy Software framework design accessible to Software framework design accessible to

studentsstudents Framework design builds on basic OO Framework design builds on basic OO

programming concepts and technologiesprogramming concepts and technologies Framework design best when carried out Framework design best when carried out

systematically and incrementally systematically and incrementally Teachers should begin with examples that are Teachers should begin with examples that are

already part of the students’ backgroundalready part of the students’ background

Page 52: Teaching Java Framework Design Using Classic Problems

5252

Cunningham Group ReferencesCunningham Group References

H. C. Cunningham, Y. Liu, and C. Zhang. “Using H. C. Cunningham, Y. Liu, and C. Zhang. “Using Classic Problems to Teach Java Framework Design,” Classic Problems to Teach Java Framework Design,” Science of Computer Programming, Science of Computer Programming, Special Issue on Special Issue on Principles and Practice of Programming in Java (PPPJ Principles and Practice of Programming in Java (PPPJ 2004), Vol. 59, No. 1-2, pp. 147-169, January 2006.2004), Vol. 59, No. 1-2, pp. 147-169, January 2006.

H. C. Cunningham, Y. Liu, and P. Tadepalli. H. C. Cunningham, Y. Liu, and P. Tadepalli. “Framework Design Using Function Generalization: A “Framework Design Using Function Generalization: A Binary Tree Traversal Case Study,” In Binary Tree Traversal Case Study,” In Proceedings of Proceedings of the ACM SouthEast Conferencethe ACM SouthEast Conference, pp. 312-318, March , pp. 312-318, March 2006. 2006.

Page 53: Teaching Java Framework Design Using Classic Problems

5353

Cunningham Group ReferencesCunningham Group References

H. C. Cunningham and P. Tadepalli. “Using H. C. Cunningham and P. Tadepalli. “Using Function Generalization to Design a Cosequential Function Generalization to Design a Cosequential Processing Framework,” In Processing Framework,” In Proceedings of the 39th Proceedings of the 39th Hawaii International Conference on System SciencesHawaii International Conference on System Sciences, , 10 pages, IEEE, January 2006.10 pages, IEEE, January 2006.

H. C. Cunningham, P. Tadepalli, and Y. Liu. H. C. Cunningham, P. Tadepalli, and Y. Liu. “Secrets, Hot Spots, and Generalization: Preparing “Secrets, Hot Spots, and Generalization: Preparing Students to Design Software Families,” Students to Design Software Families,” Journal of Journal of Computing Sciences in CollegesComputing Sciences in Colleges, Vol. 20, No. 6, pp. , Vol. 20, No. 6, pp. 74-82, CCSC, June 2005.74-82, CCSC, June 2005.

Page 54: Teaching Java Framework Design Using Classic Problems

5454

Other ReferencesOther References

D. L. Parnas. “On the Design and Development of D. L. Parnas. “On the Design and Development of Program Families,” Program Families,” IEEE Transactions on Software IEEE Transactions on Software EngineeringEngineering, Vol. SE-2, pp. 1-9, March 1976., Vol. SE-2, pp. 1-9, March 1976.

H. A. Schmid. “Framework Design by Systematic H. A. Schmid. “Framework Design by Systematic Generalization,” In Generalization,” In Building Application Building Application Frameworks: Object-Oriented Foundations of Frameworks: Object-Oriented Foundations of Framework DesignFramework Design, M. E. Fayad, D. C. Schmidt, , M. E. Fayad, D. C. Schmidt, and R. E. Johnson, Eds. Wiley, 1999, pp. 353–378.and R. E. Johnson, Eds. Wiley, 1999, pp. 353–378.

Page 55: Teaching Java Framework Design Using Classic Problems

5555

Other ReferencesOther References

D. M. Weiss and C. T. R. LaiD. M. Weiss and C. T. R. Lai. Software Product-. Software Product-Line Engineering: A Family-Based Software Line Engineering: A Family-Based Software Development ProcessDevelopment Process, Addison-Wesley, 1999., Addison-Wesley, 1999.