Deriving State…...and an example of combining behaviour.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Week 8 Recap CSE 115 Spring Composite Revisited Once we create a composite object, it can itself refer to composites. Once we create a composite.
Refactoring Overview  What is refactoring?  What are four good reasons to refactor?  When should you refactor?  What is a bad smell (relative to refactoring.
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Classes and Object- Oriented... tMyn1 Classes and Object-Oriented Programming The essence of object-oriented programming is that you write programs in.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Matt Klein 7/6/2009.  Behavioral Pattern  Intent  Allow an object to alter its behavior when its internal state changes. The object will appear to.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
Design Patterns CS is not simply about programming
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
Marcelo Santos – OOAD-CDT309, Spring 2008, IDE-MdH 1 Object-Oriented Analysis and Design - CDT309 Period 4, Spring 2008 Design Patterns: someone has already.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Design Patterns Ref : Chapter 15 Bennett et al. useful groups of collaborating classes that provide a solution to commonly occuring problems. provide.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Case Studies on Design Patterns Design Refinements Examples.
CSC 211 Introduction to Design Patterns. Intro to the course Syllabus About the textbook – Read the introduction and Chapter 1 Good attendance is the.
Design Patterns. Patterns “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution.
COMP 6471 Software Design Methodologies Winter 2006 Dr Greg Butler
CS 350 – Software Design The Strategy Pattern – Chapter 9 Changes to software, like other things in life, often focus on the immediate concerns and ignore.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
Software Engineering CS3003 Lecture 4 Code bad smells and refactoring.
Refactoring. Refactoring Overview  What is refactoring?  What are four good reasons to refactor?  When should you refactor?  What is a bad smell (relative.
REFACTORINGREFACTORING. Realities Code evolves substantially during development Requirements changes 1%-4% per month on a project Current methodologies.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
SE-2811 Software Component Design Week 1, Day 2 (and 1-3 and 2-1) SE-2811 Dr. Josiah Yoder Slide style: Dr. Hornick 1.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Henrik Bærbak Christensen1 Frameworks / Product Lines The frame for reuse.
The HotCiv GUI Instantiating the MiniDraw Framework.
Object-Oriented Programming Chapter Chapter
Test Stubs... getting the world under control. TDD of State Pattern To implement GammaTown requirements I CS, AUHenrik Bærbak Christensen2.
1 Chapter 5:Design Patterns. 2 What are design pattern?  Schematic description of design solution to recurring problems in software design and,  Reusable.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
The State Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
HotCiv Project Starting up!. Henrik Bærbak Christensen2 HotCiv = Agile development Iterations of –product development –learning increments.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Multi Dimensional Variance: How to make ultra flexible software!
Applying the Principles Two Examples. Example 1 New Requirement It would be nice with a simple GUI “to see something” instead of just xUnit tests...
Refactoring and Integration Testing or Strategy, introduced reliably by TDD The power of automated tests.
MiniDraw Introducing a Framework... and a few patterns.
Patterns are Roles What patterns are and what not…
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CS, AUHenrik Bærbak Christensen1 Compositional Design Principles The “GoF” principles Or Principles of Flexible Design.
Deriving Abstract Factory Loosening the coupling when creating objects...
Mandatory 3 Test Stubs State Abstract Factory. Stubs, Spies, and Fake Objects One Example Making distribution testable... Henrik Bærbak Christensen2.
Mandatory 3 Test Stubs State Abstract Factory. Do not panic! dSoftArk is about Good analyzable design not about HotCiv! Henrik Bærbak Christensen2.
Strategy in 15 minutes... derived from the principles.
Instantiating the MiniDraw Framework
Introducing a Framework ... and a few patterns
Design Patterns: MORE Examples
Applying the Principles
Conception OBJET GRASP Patterns
CS 350 – Software Design The Strategy Pattern – Chapter 9
Behavioral Design Patterns
Compositional Design Principles
Week 4 Object-Oriented Programming (1): Inheritance
State Design Pattern 1.
MSIS 670 Object-Oriented Software Engineering
DESIGN PATTERNS : Strategy Pattern
DESIGN PATTERNS : State Pattern
Software Engineering and Architecture
Software Engineering and Architecture
Software Engineering and Architecture
Software Engineering and Architecture
HFOOAD Chapter 5 Interlude
Software Engineering and Architecture
Software Engineering and Architecture
Software Engineering and Architecture
Software Engineering and Architecture
Presentation transcript:

Deriving State…...and an example of combining behaviour

New requirement Gammatown County wants: “In weekdays we need Alphatown rate (linear); in weekends Betatown rate (progressive)” Henrik Bærbak Christensen2CS, AU

Exercise “In weekdays we need Alphatown rate (linear); in weekends Betatown rate (progressive)” Exercise: How? Henrik Bærbak Christensen3CS, AU

Same analysis Model 1: –Source tree copy Now three copies to maintain Model 2: –Parametric If ( town == alpha ) {} else if (town == beta) {} else if (town == gamma) {} Model 3: –Polymorphic – but ??? Model 4: –Compositional – but how? Henrik Bærbak Christensen4CS, AU

But… I will return to the analysis shortly, but first… I have a problem! –I want to do TDD – because automated tests feel good… –But how can I write test first when the outcome of a GammaTown rate strategy… depends on the day of the week??? Henrik Bærbak Christensen5CS, AU

Tricky Requirement The test case for AlphaTown: … but how does it look for GammaTown? Henrik Bærbak Christensen6CS, AU

Direct and Indirect Parameters The day of the week is called an indirect parameter to the calculateTime method –It is not an instance variable of the object –It is not a parameter to the method –It cannot be set by our JUnit code  Henrik Bærbak Christensen7CS, AU

Solutions? So – what to do? –Come in on weekends? Manual testing! –Set the clock ? Manual testing! Mess up Ant as it depends on the clock going forward! –Refactor code to make Pay Station accept a Date object? No – pay stations must continously ask for date objects every time a new coin is entered… I will return to this problem set soon… Henrik Bærbak Christensen8CS, AU

Polymorphic Solutions to the GammaTown Challenge

Premise Let us assume that we have developed the polymorphic solution to handle BetaTown! That is: forget the Strategy based solution we did last time for the next hour... CS, AUHenrik Bærbak Christensen10

Revisited How did it look? CS, AUHenrik Bærbak Christensen11

So... Given this: How to make a subclass that reuse the calculateTime implementations of two different classes in the class hierarchy? Actually, we can do this in quite a number of ways CS, AUHenrik Bærbak Christensen12

Refactored design in next slides... Another approach: –Make PayStationImpl abstract, calculateTime abstract –Two subclasses, one for linear and one for progressive CS, AUHenrik Bærbak Christensen13

Model 3a: Multiple Inheritance Subclass and override! Could work in C++, but not Java or C#; –experience with join-hierarchies in C++ are bad  Henrik Bærbak Christensen14CS, AU If (isWeekend) { PSProgressive::calcTime(…); } else { PSLinear::calcTime(…); }

Model 3b: Direct Subclass Cut code from linear and progressive, paste into alternating Henrik Bærbak Christensen15CS, AU

Model 3c:Sub-sub Class Cut code from progressive, paste into alternating Henrik Bærbak Christensen16CS, AU

Code view Henrik Bærbak Christensen17CS, AU

Model 3d: Bubbling up/Superclass Make protected calculation methods in abstract PayStationImpl, and call these from Alternating –This is a classic solution often seen in practice Henrik Bærbak Christensen18CS, AU

Code view The super class Alpha Henrik Bærbak Christensen19CS, AU

Code view Gamma Discussion –No code duplication –Exercise: what are the liabilities? Henrik Bærbak Christensen20CS, AU

Liabilities Superclass maintainability –Becomes a junk pile of methods over time –The methods are unrelated to the superclass itself, it is just a convenient parking lot for them –This is an example of an abstraction with little cohesion –Grave yard of forgotten methods? Henrik Bærbak Christensen21CS, AU

Model 3e: Stations in Stations Henrik Bærbak Christensen22CS, AU

Model 3e: Stations in Stations The “pay stations in pay station” way: –Create an gamma pay station containing both an alpha and beta pay station Exercise: Benefits and liabilities? Henrik Bærbak Christensen23CS, AU

Morale It simply does not work cleanly! I have never seen a polymorphic solution that handles this very simple requirement in a natural and concise way! CS, AUHenrik Bærbak Christensen24

Compositional Variants

Premise Now, please reset your minds agains! We now look at the compositional variant (strategy pattern) that we made the last time! CS, AUHenrik Bærbak Christensen26

Code View (Java) DAIMIHenrik Bærbak Christensen27

Model 4a: Parameter + compositional Henrik Bærbak Christensen28CS, AU

Model 4a: Parameter + compositional Liabilities –Code change in the constructor –Constructor has become really weird for alpha and beta Worse: we have just blown the whole idea! –now the pay station has resumed the rate calculation responsibility  –or even worse – the responsibility is distributed over several objects    The responsibility to know about rate calculations are now distributed into two objects – leading to lower analyzabilty leads to duplicated code, and bugs difficult to track. Henrik Bærbak Christensen29CS, AU

Model 4b: Copy and paste version Cut and paste the code into new strategy object Multiple maintenance problem  –a bug in price calculation functionality must be corrected in two places – odds are you only remember one of them. Henrik Bærbak Christensen30 GammaAlternatingRateStrategy CS, AU

… on to a nice compositional solution: State pattern

Compositional Idea  I identify some behaviour that varies. –The rate calculation behaviour is what must vary for Gammatown and this we have already identified.  I state a responsibility that covers the behaviour that varies and encapsulate it by expressing it as an interface. –The RateStrategy interface already defines the responsibility to “Calculate parking time” by defining the method calculateTime.  I compose the resulting behaviour by delegating the concrete behaviour to subordinate objects. –This is the point that takes on a new meaning concerning our new requirement. Henrik Bærbak Christensen32CS, AU

Model 4 Compose the behaviour... That is: –the best object to calculate linear rate models has already been defined and tested – why not use its expertise ? Same goes with progressive rate. –so let us make a small team – one object responsible for taking the decision; the two other responsible for the individual rate calculations. Henrik Bærbak Christensen33CS, AU

The Cartoon Henrik Bærbak Christensen34 rate calculation request Team leader Rate Policy Expert Linear Rate Policy Expert Progressive 1. check clock 2.delegate to expert CS, AU

Interpretation Note: From the Pay Station’s viewpoint the behaviour of the ”team leader” change according to the state of the clock! Henrik Bærbak Christensen35 rate calculation request Pay Station Team leader CS, AU

Clock State Define Behavior Reusing existing, well tested, classes... Henrik Bærbak Christensen36CS, AU

Code view Henrik Bærbak Christensen37 In AlternatingRateStrategy: In AlternatingRateStrategy: Construction 1. check clock 2.delegate to expert CS, AU

Analysis Consequence: –Minimal new code, thus very little to test most classes are untouched, only one new is added. –Change by addition, not modification –No existing code is touched so no new testing no review –Parameterization of constructor All models possible that differ in weekends... Henrik Bærbak Christensen38CS, AU

Roles revisited This once again emphasizes the importance of –  Encapsulate what varies: the rate policy –  Define well-defined responsibilities by interfaces –  Only let objects communicate using the interfaces Then the respective roles (pay station / rate strategy) can be played by many difference concrete objects And each object is free to implement the responsibilities of the roles as it sees fit – like our new ‘team leader’ that does little on his own! –  also to let most of the dirty job be done by others Henrik Bærbak Christensen39CS, AU

The State Pattern

Analysis Yet another application of –(but note that the argumentation this time was heavily focused on the  aspect: composing behaviour by delegating to partial behaviour) Rephrasing what the Gammatown pay system does: –The rate policy algorithm alters its behaviour according to the state of the system clock Henrik Bærbak Christensen41CS, AU

State Pattern State pattern intent –Allow an object to alter its behaviour when its internal state changes. The object will appear to change its class. –The rate policy algorithm alters its behaviour according to the state of the system clock –Seen from the PayStationImpl the AlternatingRateStrategy object appears to change class because it changes behaviour over the week. Henrik Bærbak Christensen42CS, AU

Roles Context delegate to its current state object State specifies responsibilities of the behaviour that varies according to state ConcreteState defines state specific behaviour State changes? –May be defined either in Context or in ConcreteState set –That who defines it is less reusable Henrik Bærbak Christensen43CS, AU

Exercise Which object/interface fulfil which role in the pay station? Who is responsible for state changes? Henrik Bærbak Christensen44CS, AU

Benefits/Liabilities of State General –State specific behaviour is localized in a single ConcreteState object –State changes are explicit as you just find the assignments of ‘currentState’ –Increased number of objects as always with compositional designs Compare common statemachines: –case INIT_STATE: –case DIE_ROLL_STATE: Henrik Bærbak Christensen45CS, AU

Examples All state machines can be modelled by the state pattern –and looking for them there are a lot –TCP Socket connection state –any game has a state machine –Protocols –etc... Henrik Bærbak Christensen46CS, AU

Example: Turnstile CS, AUHenrik Bærbak Christensen47

Summary New requirement –a case that screams for reusing existing and well- tested production code –cumbersome to utilize the reuse potential especially in the subclassing case (deeper discussion in the book) –but handled elegantly by compositional design think in terms of teams of objects playing different roles –I derived the State pattern more general pattern handling state machines well Henrik Bærbak Christensen48CS, AU