Your SlideShare is downloading. ×
Design Patterns Explained: From Analysis through Implementation
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Design Patterns Explained: From Analysis through Implementation

315

Published on

Alan Shalloway takes you beyond thinking of design patterns as “solutions to a problem in a context.” Patterns are really about handling variations in your problem domain while keeping code from …

Alan Shalloway takes you beyond thinking of design patterns as “solutions to a problem in a context.” Patterns are really about handling variations in your problem domain while keeping code from becoming complex and difficult to maintain as the system evolves. Alan begins by describing the classic use of patterns. He shows how design patterns implement good coding practices and then explains key design patterns including Strategy, Bridge, Adapter, Façade, and Abstract Factory. In small group exercises, learn how to use patterns to create robust architectures that can readily adapt as new requirements arise. Lessons from these patterns are used to illustrate how to do domain analysis based on abstracting out commonalities in a problem domain and identifying particular variations that must be implemented. Leave with a working understanding of what design patterns are and a better way to build models of your application domains.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
315
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
16
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1.     MI Half‐day Tutorial  6/3/2013 8:30 AM              "Design Patterns Explained: From Analysis through Implementation"       Presented by: Alan Shalloway Net Objectives               Brought to you by:        340 Corporate Way, Suite 300, Orange Park, FL 32073  888‐268‐8770 ∙ 904‐278‐0524 ∙ sqeinfo@sqe.com ∙ www.sqe.com
  • 2. Alan Shalloway Net Objectives With more than forty years of experience, the founder and CEO of Net Objectives Alan Shalloway is an industry thought leader in lean, kanban, product portfolio management, Scrum, and agile design. Alan helps companies transition enterprise-wide to lean and agile methods, and teach courses in these areas. He is the primary author of Lean-Agile Software Development: Achieving Enterprise Agility, Design Patterns Explained, Lean-Agile Pocket Guide for Scrum Teams, and Essential Skills for the Agile Developer. Cofounder and board member for the Lean Software and Systems Consortium, Alan is a popular speaker at prestigious conferences worldwide.  
  • 3. Design Patterns Explained Analysis to Implementation Al Shalloway, CEO Net Objectives copyright © 2010 Net Objectives Inc. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 1
  • 4. Lean for Executives Product Portfolio Management Business Product Owner Scaled Agile Framework Business ASSESSMENTS CONSULTING T RAINING COACHING Lean Enterprise Manage ment Team technical process Lean-Agile Kanban / Scrum ATDD / TDD / Design Patterns Lean Management Project Management Purpose of This Tutorial – Provide an innovative look at Design Patterns – Incorporates:  Object-Oriented Principles – a “new” way to look at object-oriented design – a better way to identify and define our entities  The general design advice patterns represent – Consider how domain analysis can enhance design – Consider the difference between  Knowing Patterns  Being “Pattern-Oriented” Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 2
  • 5. What Tutorial Covers – Basic object-oriented principles  Encapsulation  Polymorphism  Inheritance – What to use it for  General Advice from the “Gang of Four” – Design patterns – what they really are – Learn why design patterns are good designs – Learn how to use design patterns together When Adding Functionality – Where’s the Problem?  In writing the new code?  In integrating it into the new system?  Which is likely to be the source of difficulties?  Why? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 3
  • 6. In a Nutshell  How can we design to accommodate change?  We are not trying to anticipate change, per se, as much as writing our code to accommodate change better – Trying to anticipate change can lead to “paralysis by analysis”  Designing from context will guide us as to when we need to get the details. It also gives us the bigger picture from within which to design Design Patterns copyright © 2010 Net Objectives Inc. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 4
  • 7. What Are Patterns?  Patterns are best-practice solutions for recurring problems in a particular context.  Patterns have been classified as being:* – Architectural – Design – Idiomatic  Design patterns can also be thought of as describing the relationships between the entities (objects) in our problem domain.  Patterns have led to new modeling techniques: – handling variations in behavior – new ways of using inheritance to avoid rigidity and aid testing and maintenance issues. * Pattern Oriented Software Architecture, Buschmann, et. al. Drawer Front Top Please Don’t Turn the Page Until Instructed to Do So Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 5
  • 8. A Pattern in Carpentry  Let’s say two carpenters are trying to decide on how to  build a dresser. One says to the other: “should we build the joint by first cutting down, then cutting up at a 45 degree angle...”  “then back down and back up the other way, then back down” Dove-Tail  Tails and Pins  Reliable  Strong  Humidity Tolerant Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 6
  • 9. A Miter Joint Commonly used in picture frames. Patterns Work At All Levels Dovetail Miter Forces Strong, High-Cost, Decorative, Humidity Tolerant Weak, Cheap, Fast, Good for Picture Frames Design Interlaced joint Single Abutting Cut Implementation Cut teeth, .5" long, .4" 45 degree angle cut deep, match teeth to gaps attached with staple or other spanning connector Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 7
  • 10. Focusing on Detail Loses the Big Picture  By having to describe how we implement the dove-tail  joint, we can lose sight of why we might want to use it in the first place. Dove-tail Joint vs. Miter Joint emphasizes: – do we want a strong, relatively expensive joint that is of high quality and will last forever – or do we want a weak, relatively inexpensive joint that is easy to make but not of high quality The Different Perspectives  Conceptual – describes what you want, not how you’ll get it – requirements are often specified at a conceptual level – “we need to handle inventory in LIFO, FIFO, avg cost”  Specification – the interfaces of our classes – how objects “talk” to each other – our product class’ methods look like …  Implementation – the code itself Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 8
  • 11. Consider These Are they the same or different? Mop Broom Sponge Same or Different?  Who thinks they are the same?  Who thinks they are different? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 9
  • 12. As Any Good Consultant Will Tell You: “IT DEPENDS!”  As specific objects: they are different  As a concept: they are all Cleaning Utensils Where does “Cleaning Utensil” exist? Not in the real world, but in our thoughts as an abstraction classification! A “Cleaning Utensil” does not exist, but specific kinds do! Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 10
  • 13. Three Levels of Perspective*  Conceptual Perspective  Specification Perspective  Implementation Perspective * From Martin Fowler’s UML Distilled A Note About Encapsulation  We often think of encapsulation as something we do at    the object level (i.e., hide its data). On reflection, however, we can see that we have used encapsulation to hide a set of classes (all the derived classes). Abstract classes and interfaces essentially encapsulate all of their derivations and implementations -- no one need know they exist. Encapsulation can be used to contain rules - good idea to put one rule in one place Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 11
  • 14. Commonality-Variability Analysis  James Coplien’s “Multi-paradigm Design for C++” – “Abstraction, in the common English language sense, means to focus on the general and put aside the specific. We abstract by emphasizing what is common and de-emphasizing details. Abstraction is a fundamental analysis tool.” His thesis is on line at: http://www.netobjectives.com/files/CoplienThesis.pdf (link is case-sensitive) Commonalities  “Commonality analysis is the search for common elements that helps us understand how family members are the same” *  Commonalities are – Recognized from experience – Learned through analysis (abstracted)  Commonalities can define basic concepts in a domain * Multi-Paradigm Design in C++, Jim Coplien Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 12
  • 15. Variability Analysis  Variability makes sense only in a given commonality frame of reference. It is a variation of some commonality – “From an architectural perspective, commonality analysis gives the architecture its longevity; variability analysis drives its fitness for use”* * Multi-Paradigm Design in C++, Jim Coplien Reasons to Get Variations of Commonalities  In analysis, we don’t need detailed design, we just need to determine: – The resources required for implementation – The risks involved  Define scope (variations give us specific cases)  Make sure variations define commonalities (do we have enough cases to define the interface?) ~3 Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 13
  • 16. Example Problem copyright © 2010 Net Objectives Inc. The Problem  We are writing a web-enabled sales order system  A customer signs in and fills out the order Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 14
  • 17. Initial Solution TaskController SalesOrder Have TaskController instantiate SalesOrder that handles filling out the sales order, etc. The Challenge  As soon as we get new variations in tax we have to  modify our SalesOrder object Where should we add the new responsibility if taxation begins to vary? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 15
  • 18. New Requirement Multiple Tax Domains Eventually need to handle different tax rules •US Tax •Canadian Tax One Solution method calcTax // // // // // // // use switch on type of tax rule to be used TYPE US: calc tax based on US rules break TYPE CANADIAN: calc tax based on Canadian rules break Direct Inheritance for Specialization  We can solve this problem by specializing our first SalesOrder object to handle the new tax rules TaskController original calcTax that does US tax SalesOrder + calcTax() new (overriden) calcTax that does Canadian tax CanadianSalesOrder + calcTax() Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 16
  • 19. Abstract Inheritance for Specialization  This is a bit better… SalesOrder + calcTax() CanadianSalesOrder USSalesOrder + calcTax() + calcTax() This May Lead to Maintenance Problems  If we get new variations, where do we put them?  We either start using lots of switches (which makes the  code difficult to understand), or we start overspecializing (which still makes things difficult) What if we need to switch tax algorithms at runtime? SalesOrder + calcTax() CanadianSalesOrder USSalesOrder + calcTax() + calcTax() EnglishCanadianSO FrenchCanadianSO + language() language() Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 17
  • 20. Advice From the Gang of Four copyright © 2010 Net Objectives Inc. Advice from the Gang of Four Design to interfaces Favor object delegation over class inheritance Consider what varies in your design … and “encapsulate the concept that varies” Gamma, Helms, Johnson, Vlissides: Design Patterns: Elements of Reusable Object-Oriented Design Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 18
  • 21. Design to Interfaces: Methods Craft method signatures from the perspective of the consuming entities Hides the implementation of your methods Programming by intention is a systematized way of designing to interfaces Design to Interfaces →1 or 1→many 1 AbstractionA Impl1 Impl2 Impl3 Relationship Relationship AbstractionB Impl4 Copyright © 2007 Net Objectives. All Rights Reserved. Impl5 12 April 2013 19
  • 22. Favor delegation over inheritance specializing function with inheritance is a short path to problems Proper use of inheritance Define a class that encapsulates variation, contain (via delegation) an instance of a concrete class derived from the abstract class defined earlier Chip Chip_64e Chip_128e Class Inheritance to Specialize Chip Encryption 64e 128e Class Inheritance to Categorize 1. Decoupling of concepts 2. Deferring decisions until runtime 3. Small performance hit Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 20
  • 23. Find what varies and encapsulate it Base classes encapsulate their implementing subclasses This encapsulates varying behavior Chip Encryption 64 128 Find what varies and encapsulate it  A varying anything: – Varying design – Varying object creation – Varying relationships (1-1, 1-many) – Varying sequences and workflows – Etc… Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 21
  • 24. Encapsulate variations Encapsulating variation means to make it appear as if the varying issue is not varying Each pattern encapsulates a different varying thing The Net Objectives Patterns Repository Behavior Strategy Bridge Template Method Null Object Sequence Decorator Chain of Responsibility Template Method __ Workflow Template Method Visitor Bridge Null Object Cardinality Decorator Chain of Responsibility Proxy Observer Construction Singleton Abstract Factory __ __ Selection Chain of Responsibility __ __ __ Structure Composite Template Method __ __ Entity Facade Adapter Proxy __ Relationships Observer Command Mediator Visitor Dependencies Mock Object __ __ __ Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 22
  • 25. This Advice Relates to Principles  Deal with things at an abstract level  Why? Client AbstractionA Impl4 Relates to: Impl1 Impl2 Impl3 The Open-Closed Principle This Advice Promotes Quality  Design to Interfaces: – Helps eliminate redundant relationships – Avoids subclass coupling  Encapsulate Variation – Promotes encapsulation – Decouples client objects from the services they use – Leads to component-based architectures  Favor aggregation over inheritance – Promotes strong cohesion – Helps eliminate redundant implementation Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 23
  • 26. At First Level of Understanding Design Patterns Are Examples  Each pattern is an example of a design that follows this general advice well, in a given context  Design patterns are discovered, not invented: they are what successful design have done to solve the same problem  Studying design patterns is a good way to study good design, and how it plays out under various circumstances The Strategy Pattern copyright © 2010 Net Objectives Inc. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 24
  • 27. The Strategy Pattern  We need different behavior at different times; either for different things we are working on or for different clients asking us to do work.  GoF Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. * Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, Vlissides. AddisonWesley Professional. 1995. The Strategy Pattern  The Strategy pattern is a pattern that tells us how to identify a set of rules that conceptually do the same thing  In our example: tax – identify a common way to communicate with all implementations of the rule – define an interface or abstract class that defines this communication – implement each variation of the rule as an implementation or derivation Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 25
  • 28. Strategy Lives in Analysis, Design, Implementation  In analysis: – Any time we find a varying business rule, it is likely a Strategy pattern is present – If we know we need to use a Strategy, the pattern tells us to encapsulate the varying rule behind an interface  During implementation – The pattern gives “instant experience” in the implications of one implementation over another  The pattern is really about the relationship between one object that uses one of several conceptually similar rules In The UML TaskController SalesOrder CalcTax + taxAmount(itemSold : Salable, qty : double, price : double) : double USTax CanTax Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 26
  • 29. The Canonical Strategy Pattern Context Strategy + request(Strategy) Client + algorithm() StrategyA + algorithm() StrategyB + algorithm() Strategy as an Example of GoF Approach Client (3) Context + request(Strategy) Strategy + algorithm() (2) encapsulates variation (1) StrategyA + algorithm() (1) StrategyB + algorithm() (1) find what varies (the strategies) and (2) encapsulate it (Strategy) (3) favor object-aggregation over class-inheritance Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 27
  • 30. Who Knows Which Rule to Use  Before, TaskController needed to know either the  value of the tax switch to set or which SalesOrder to instantiate It can now instantiate the appropriate CalcTax object  OR, we can have a creational object (factory) make the proper CalcTax object Another Version of the Strategy Pattern * Context Strategy + request(Strategy) Client + algorithm() 1 Factory StrategyA + algorithm() StrategyB + algorithm() Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 28
  • 31. What Happens Now With Changing Requirements  If we get a new tax requirement, we : 1. Derive the new class from the CalcTax class 2. Modify the TaskController or the Factory object  Which may, in fact, work with a data dictionary so even it doesn’t need to change  No other objects change Value of Strategy     Conceptually it is cleaner Each object is concerned with one function Better independence of different actions Issues that are separated into different encapsulated entities also makes unit testing easier Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 29
  • 32. Why Bother?  What happens if many things vary?  In other words, in addition to the tax rules, we could have the following variations? – different shipping charges – different monetary rules – different address rules  Switches and direct inheritance do not scale Code Qualities Where Good Design Begins What Good Design Reflects Why Patterns are What they Are copyright © 2010 Net Objectives Inc. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 30
  • 33. Qualities  Consider a string of  Christmas lights What do you do if it fails… – On the Table? – On the Tree?  Is this a complex device?  It’s not so much the complexity as it is the: – Dependencies – Fragility – Duplication Predictability  We can’t predict how our requirements are going to change  We can predict how different coding styles will adapt to unpredictable requirements changes  What is the style that adapts more readily? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 31
  • 34. Another One: Who Thinks We Spend a lot of Time Fixing Bugs? The Time on Bugs Myth  We usually spend very little time fixing bugs…  We OFTEN spend a lot of time finding bugs and in the discovery process of seeing how things affect each other  We should therefore put our efforts more into finding errors when they occur than worrying about the amount of typing we do Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 32
  • 35. Many Factors to Consider  What are the first principles? Cohesion  Cohesion refers to how “closely the operations in a routine [or  class] are related.” I have heard other people refer to cohesion as “clarity” because the more operations are related in a routine [or class] the easier it is to understand the code and what it's intended to do. * Strong cohesion is related to clarity and understanding  No "schizophrenic classes”  No "12-page methods" * Code Complete, Steve McConnell, 1993, p. 81. This concept was first described by Larry Constantine in 1975, but we like McConnell’s definition best. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 33
  • 36. Strong Cohesion  Class Cohesion – A class has a single responsibility – Practice: Commonality/Variability Analysis (tomorrow)  Method Cohesion – Each method is a single function – Practice: Programming by Intention (next slide) Coupling  Coupling refers “to the strength of a connection between two routines [or classes]. Coupling is a complement to cohesion. Cohesion describes how strongly the internal contents of a routine [or class] are related to each other. Coupling describes how strongly a routine is related to other routines. The goal is to create routines [and classes] with internal integrity (strong cohesion) and small, direct, visible, and flexible relations to other routines [and classes] (loose coupling).”*  Tight coupling is related to highly interconnected code * Code Complete, Steve McConnell, 1993, p. 81. This concept was first described by Larry Constantine in 1975, but we like McConnell’s definition best. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 34
  • 37. No Redundancy  "One Rule in One Place"  Good example of violating this: – Y2K  Redundancy is not just: – Redundant state – Redundant functions  It can also be redundant relationships, design, construction, etc… Connection(url); _______ = new Connection(url, port);  Anything that you would have to change in more than one place Encapsulation and Other Qualities  Encapsulation and Coupling – Hidden things cannot be coupled to  Encapsulation and Cohesion? – Cohesive issues are easier to hide  Encapsulation and Redundancy? – When an issue is hidden, multiple clients cannot make use of the same behavior – When it’s revealed, then no duplication is needed – It's an issue of balance Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 35
  • 38. Encapsulation, Coupling, and Redundancy Class A -Redundant Issue Class B -Redundant Issue Class A and Class B have a redundant bit of state or functionality, or a redundant relationship to another object The redundant issue is currently encapsulated, however How can we resolve this redundancy? It Depends! Class A -Redundant Issue Class B -Redundant Issue …on the relationship between these classes  Is it: – Conceptual? Are classes A and B variations of some common concept? or – A relationship of consistent use? Are classes A and B two distinct entities that have a need that can be resolved in a common way? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 36
  • 39. Using Inheritance Still encapsulated from other objects SuperClass Conceptual #Redundant Issue Class A Class B Concrete We could use Inheritance. So long as we don't mind coupling these classes to a superclass, this resolves the redundancy while keeping the Issue encapsulated Using Delegation Class A Class C +Redundant Issue Class B Must be public for Class A and Class B to use it We could use Delegation. This exposes the “Redundant issue” as the interface of the service class (Class C). However, remember, the rule is “encapsulate by policy, reveal by need”. Eliminating redundancy is a definite need. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 37
  • 40. Patterns Promote Quality Context Strategy + request(Strategy) Client + algorithm() StrategyA Factory + algorithm() StrategyB + algorithm() Cohesion: Each class is focused on a single responsibility Coupling: Base Strategy hides concrete types Redundancy : Anything common pushed into the base class Encapsulation: Factory hides types, design, implementation How the GoF Advice Promotes Quality  Design to Interfaces:  Helps eliminate redundant relationships  Avoids subclass coupling  Encapsulate Variation  Promotes encapsulation  Decouples client objects from the services they use  Leads to component-based architectures  Favor aggregation over inheritance  Promotes strong cohesion  Helps eliminate redundancies  Makes designs more dynamic Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 38
  • 41. Testability and Design copyright © 2010 Net Objectives Inc. Testability and Design  Considering how to test your objects before designing them is, in fact, a kind of design  It forces you to look at: – The public method definitions – What the responsibilities of the object are  Easy testability is tightly correlated to loose coupling and strong cohesion Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 39
  • 42. Testability  Code that is difficult to unit test is often: – Tightly Coupled: "I cannot test this without instantiating half the system" – Weakly Cohesive: "This class does so many things, the test will be enormous and complex!" – Redundant: "I'll have to test this in multiple places to ensure it works everywhere" The Role of Testability  Unit testing is a good thing. You should do it  Whether you agree or not – You should always ask yourself "if I were to test this, how would I do it?" – If you find the design would be very hard to test, or if you cannot see a way to test it, ask yourself "why isn't this more testable?"  This is a thought process that can capture coupling, cohesion, and redundancy issues that you might otherwise miss Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 40
  • 43. Trim Tabs "If you try to change the course of a supertanker by pushing at the bow you will not see any change. If you push on the rudder your chances of changing the course of the supertanker are guaranteed, but the amount of energy needed is still prohibitive. To be the most effective we need to push on the trim tabs, those small fins on the end of the rudder, by moving them, the rudder in turn moves and the tanker makes its turn.” R. Buckminster Fuller "Critical Path" ~3 Testable? Factory Context Strategy + request(Strategy) Client + algorithm() StrategyA + algorithm() StrategyB + algorithm() MockStrgy + algorithm() Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 41
  • 44. “Design” Patterns  Patterns are not just about “Design”  They are used in – – – – – – Architecture Design Testing Deployment Refactoring …and analysis The Analysis Matrix copyright © 2010 Net Objectives Inc. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 42
  • 45. Motivation  Information overload – Too much information – Chaotically arranged – Not sure how to organize it – Not sure how to begin Motivation Example  Designing a document control system that includes documents from: – All airlines – Most manufacturers  Boeing, McDonnell Douglas  Pratt & Whitney, Rolls Royce, GE – About 100 cases all told – Documents are conceptually the same  Collection of text and graphics  Version control required Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 43
  • 46. Example Requirements Rolls-Royce Boeing 1a 1-1a 1-1 1-2 1b -1 1-3a 1a -1 1c-1 ~s Handling Variation: A Case Study Let’s say we’ve been given these requirements:  We have to build a sales order system for Canada and the United States. We want to calculate freight based on the country we’re in. Money will also be handled by the country we are in. In the US, tax will be calculated by the locale. Use US and Canadian Postal rules for verifying addresses. In Canada, use GST and PST for tax. Use Canadian shipper Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 44
  • 47. Break Requirements into Cases  Distilling the requirements into cases: – CASE 1: USA Customer  Calculate freight based on UPS charges, use US Postal rules for verifying addresses and calculate tax based on sales and/or services depending upon locale. Handle money in US $. – CASE 2: Canadian Customer  Use Canadian $. Use Canadian Postal rules. Use Canadian shipper and calculate tax based on GST and PST. How to Start the Design  We want to find what varies and encapsulate it  Each column represents a given case  Each row is used to represent the concept that case is an example of  We can start with a single requirement, and build this as we go. This can be much easier to manage Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 45
  • 48. Start with One In the US, we calculate freight based on UPS charges Requirement (concept) One way to do it, in one case US Sales use UPS rates calculate freight Continue… In the US, we use US Postal rules for verifying addresses calculate freight verify address US Sales use UPS rates use US Postal rules Different Concept Same Case Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 46
  • 49. Continue… In the US, we calculate tax based on sales and/or services depending upon locale In the US we Handle money in US$ calculate freight verify address calculate tax money More Concepts US Sales use UPS rates use US Postal rules use state and local taxes US $ More Implementations for this Case Handle Canadian Case calculate freight verify address calculate tax money US Sales use UPS rates use US Postal rules use state and local taxes US $ Existing Concept Canadian Sales Canadian $ New Case In Canada we Use Canadian$ Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 47
  • 50. Next Canadian Case calculate freight verify address calculate tax money US Sales use UPS rates use US Postal rules use state and local taxes US $ Existing Concept Canadian Sales Canadian Postal Rules Canadian $ Same Case In Canada we use Canadian Postal rules. All Cases Handled calculate freight US Sales use UPS rates verify address use US Postal rules calculate tax use state and local taxes US $ money Canadian Sales use Canadian shipper use Canadian Postal rules use GST and PST Canadian $ In Canada we use a Canadian shipper In Canada we calculate tax based on GST and PST “That’s all I can think of, so I guess that’s it” Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 48
  • 51. A Note about Customers  They usually know their problem domains very well  They often use the term “All” for “the most common cases”  “Always” means “usually”, or “we always have”  “Never” means “seldom”, or “we never have” The German Case  CASE 3: German Customer – Use a German shipper, which has a maximum weight of 30 kilograms. Use Value Added Tax for taxes, European postal rules, and the dd/mm/yy date format. Currency used will be the Euro Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 49
  • 52. New Case: German Sales calculate freight verify address calculate tax money date format max weight US Sales use UPS rates use US Postal rules use state and local taxes US $ mm/dd/yyyy Canadian Sales use Canadian shipper use Canadian Postal rules use GST and PST German Sales use German shipper use European Postal rules use VAT Canadian $ dd/mm/yyyy Euro dd/mm/yyyy 30 kg Are there maximum weights in US and Canada? Maybe not. Maybe so, and the customer forgot to mention them Now I have a good, specific question to ask My customers are good at answering specific questions Can Check Our Understanding calculate freight verify address calculate tax money date format max weight US Sales use UPS rates use US Postal rules use state and local taxes US $ mm/dd/yyyy 70 lbs Canadian Sales use Canadian shipper use Canadian Postal rules use GST and PST German Sales use German shipper use European Postal rules use German VAT Canadian $ dd/mm/yyyy none Euro dd/mm/yyyy 30 kg "Sometimes yes, sometimes no…" Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 50
  • 53. Does Get More Complicated  Imagine there is a more complicated relationship between two concepts (say between calculating freight and address verification) in the US but not in the other cases  Sometimes we can do a “drill down” to capture the extra complexity, when it is not needed in all cases Use Mini-Matrix for Complex Cases calculate freight US Sales use UPS rates verify address use US Postal rules calculate tax use state and local taxes US $ money Calculate freight Verify Address Canadian Sales use Canadian shipper use Canadian Postal rules use GST and PST Canadian $ Use UPS Use US Postal Rules no PO Boxes $5.00 Use FedEx Use US Postal Rules Pick-up charge Use USPS Use US Postal Rules N/A Max weight 50 lbs 70 lbs No maximum Copyright © 2007 Net Objectives. All Rights Reserved. $4.00 12 April 2013 51
  • 54. Do Not Really Need Table  Calculate Freight – UPS Rates – USPS Rates – FedEx Rates  Verify Address – US Postal rules – US Postal rules with no PO Boxes  Pick-up Charge – none – $5.00 – $4.00  Max Weight – 50 lbs – 70 lbs – No maximum ~3 How to Use the Analysis Matrix  Note how each column in the analysis matrix represents one particular case. In our case, this represents one country  Each Row is a concept that cuts across all cases  Each entry can be thought of as an object Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 52
  • 55. Thinking of Elements as Objects calculate freight verify address calculate tax money date format max weight US Sales USCalcFreight Canadian Sales CanCalcFreight German Sales GermCalcFreight USAddrRules CanAddrRules GermanAddrRules USCalcTax USMoney Date_mmddyy USMaxWght CanCalcTax CanMoney Date_ddmmyy CanMaxWght GermanCalcTax GermanMoney Date_ddmmyy GermanMaxWght How to Use the Analysis Matrix  Each row represents different ways a rule may be implemented across all of the cases  This sounds quite a bit like a Strategy pattern – At least at this level  It can be implemented as such  How do we handle the instantiation of the appropriate strategy objects? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 53
  • 56. Using the Strategy Pattern US Sales Canadian Sales German Sales The objects in this row can be implemented as a Strategy pattern encapsulating the “calculate freight” rule. calculate freight verify address The objects in this row can be implemented as a Strategy pattern encapsulating the “verify address” rule. calculate tax The objects in this row can be implemented as a Strategy pattern encapsulating the “calculate tax” rule. money We can use Money objects that can contain Currency and Amount fields that automatically convert as needed.. date format We can use Date objects that can display as required for the country the customer is in. max weight The objects in this row can be implemented as a Strategy pattern encapsulating the “max weight” rule. Concrete Implementation Rules: Columns US Sales Canadian Sales German Sales money date format max weight Copyright © 2007 Net Objectives. All Rights Reserved. These implementations are used when we have a German customer. calculate tax These implementations are used when we have a Canadian customer. verify address These implementations are used when we have a US customer. calculate freight 12 April 2013 54
  • 57. How Sales Order Will Work TaskController SalesOrder CalcTax +taxAmount():double USTax CanTax GermanTax ...and then, a miracle occurs AddressRules +validate():boolean USAddr CalcFreight CanAddr GermanAddr +rate():double USFreight CanFreight GermanFreight How Can We Control Instantiation?  We have two issues to deal with: 1. Using the desired objects in a de-coupled way 2. Instantiating the correct set  To instantiate the correct set we need a way to instantiate a “family” of objects  We can see the "sets" now, in our design, which gives us a motivation in how we create them  Which object factory does that? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 55
  • 58. The Abstract Factory copyright © 2010 Net Objectives Inc. The Abstract Factory Pattern  We need to create families of objects for particular situations. That is, particular clients need particular sets of instantiations  GoF Intent: Provide an interface [a set of methods] for creating families of related or dependent objects without specifying their concrete classes* *Design Patterns, Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 56
  • 59. The Abstract Factory Pattern  The Abstract Factory pattern gives us a way to instantiate the legitimate a set of objects corresponding to a particular case  It will build the allowable combinations only  …but it also encapsulates something else… The “Cases” are hidden a F I n t c t y or US Case ... e r Canada Case f a ce Here, we hide “country”. The notion only appears in the factory. What’s the advantage? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 57
  • 60. Classes of the Abstract Factory The "Abstract Factory"  Why is this pattern called "The Abstract Factory"? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 58
  • 61. Using the Abstract Factory US Sales Canadian Sales German Sales money date format max weight These objects can be coordinated with the use of the Abstract Factory pattern. calculate tax T These objects can be coo rdinated with the use of the Abstract Factory pattern. verify address These objects can be coordinated with the use of the Abstract Factory pattern. calculate freight Abstractions The Abstract Factory in Action Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 59
  • 62. The Abstract Factory in Action The Abstract Factory in Action Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 60
  • 63. The Abstract Factory in Action The US Case: Sequence Diagram Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 61
  • 64. The Canada Case: Sequence Diagram C# Implementation of Factories abstract class AbstractFactory { abstract CalcTax MakeCalcTax(); abstract CalcFreight MakeCalcFreight(); abstract AddressRules MakeAddrRules(); public static AbstractFactory GetAFtoUse(customerID){ // Decide whether to return // instance of USAF CanAF } } class USAF : AbstractFactory { public override CalcTax MakeCalcTax() { return new USTax(); } public override CalcFreight MakeCalcFreight() { return new USFreight(); } public override AddressRules MakeAddrRules() { return new USAddr(); } } class CanAF : AbstractFactory { public override CalcTax MakeCalcTax() { return new CanTax(); } public override CalcFreight MakeCalcFreight() { return new CanFreight(); } public override AddressRules MakeAddrRules() { return new CanAddr(); } } class SalesOrder { private CalcTax myTax; private CalcFreight myFreight; private AddressRules myAddr; public SalesOrder (AbstractFactory myAF) { myTax= myAF.MakeCalcTax(); myFreight= myAF.MakeCalcFreight(); myAddr= myAF.MakeAddrRules(); } } Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 62
  • 65. C# C# Interfaces interface CalcTax { public double CalcTax (double qty, int id); } interface AddressRules { public bool Verify (Address myAddress); } interface CalcFreight { public double CalcFreight ( string fromCode, string toCode, string frghtClass, double weight); } C# Putting It Together // In the tier controller, or similar AbstractFactory myAF = AbstractFactory. getAFtoUse( customerID); mySalesorder = new SalesOrder( myAF); // mySalesorder is now set up to use the correct strategies, etc. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 63
  • 66. What Variations Can Occur?  What if we add a new country – Uses existing variations (France uses Euro)  New Factory for France  Use existing Euro object – Has a new implementation of a concept (no VAT in Italy)  New Factory for Italy  New "ItalyTax" object – Have a new requirement for UK only  Certain products (pharmaceuticals) pay no tax if over 65  How can you avoid changing the interface of calcTax? – Introduces a brand new concept (China!)  Trade Restrictions in China  Everything will have to be maintained Vulnerability  In design, our greatest vulnerability is often: A wrong or missing abstraction Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 64
  • 67. A Note on the Abstract Factory  The Abstract Factory Pattern says to define an interface for the instantiation of objects  In practice, there are several ways to implement an Abstract Factory Abstract Factory Variations 1. Extend an abstract type 2. Make a concrete factory object where each creation method contains a switch (based on a common variable: nationality) 3. Make a concrete factory object that is driven from a configuration file 4. Use run-time class loading driven by a database Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 65
  • 68. C# Single Object with Switch // do same for each method CalcTax makeCalcTax (string ID) { optionNum= Config.getCalcTaxOption(ID); switch (optionNum) { case option1: return new CalcTax1(); case option2: return new CalcTax2(); . . . } } // do same for each method ~3 C# Single Object with Database CalcTax makeCalcTax (string ID) { string record[]; record= Database.getRecord( ID); string classToInstantiate; classToInstantiate= record[CALC_TAX]; // CALC_TAX // holds column # //instantiate the object //classToInstantiate needs to be in Namespace.class format CalcTax myCalcTax = (CalcTax) Activator.CreateInstance(Type.GetType(classToInstantiate)); } ~3 Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 66
  • 69. The Adapter Pattern copyright © 2010 Net Objectives Inc. The Adapter Pattern  We need to change the interface of a class that has the right stuff but has the wrong interface  GoF Intent: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces* *Design Patterns, Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 67
  • 70. Our Problem Shape + setLocation() + getLocation() + display() + fill() + setColor() + undisplay() Point Line Square + display() + fill() + undisplay() + display() + fill() + undisplay() + display() + fill() + undisplay() What We Have XX_Circle + set_location() + get_location() + display_it() + fill_it() + set_its_color() + undisplay_it() Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 68
  • 71. What We Want  XX_Circle to behave like a Shape to a Client object  Unfortunately, we cannot get polymorphism with XX_Circle: XX_CIRCLE = Shape Our Problem  Our client can’t behave with our XX_Circle in the  same way it does with the Square because XX_Circle is not a Shape Author of XX_Circle may not be willing or able to change XX_Circle’s interface Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 69
  • 72. How to Implement the Pattern Shape + setLocation() + getLocation() + display() + fill() + setColor() + undisplay() Point Line Square Circle XX_Circle + display() + fill() + undisplay() + display() + fill() + undisplay() + display() + fill() + undisplay() + display() + fill() + getLocation() + setLocation() + setColor() + undisplay() + set_location() + get_location() + display_it() + fill_it() + set_its_color() + undisplay_it() If circle contained an XX_circle, it could handle the "communication’ with the client and let XX_circle handle the work C# Example class Circle : Shape { … private XX_circle pxc; … public Circle () { pxc= new XX_circle(); } public void override display() { pxc.display_it(); } } Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 70
  • 73. General Approach  If we want a client object to work with objects from two other classes we are writing in the same way without "knowing" which one it has, then either: – We create an Interface (if we’re in Java or C#) or an abstract class – And have each class implement/derive from the interface/abstract class  If we are using objects from two classes, then we may need to adapt one or both of them  This is also called "wrapping“ – but the more specific terms is preferred (decorators, proxies, and façades are also called “wrappers”) The Bridge Pattern copyright © 2010 Net Objectives Inc. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 71
  • 74. The Bridge Pattern  GoF Intent: De-couple an abstraction from its implementation so that the two can vary independently *  The normal reaction to reading this is: “Huh?"  Mine was: “How come I understand every word in this sentence but I have no idea what it means?” *Design Patterns, Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides Rectangle Drawing Program Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 72
  • 75. C# Code Example abstract class Rectangle { private int _x1, _y1, _x2, _y2; void public Draw () { DrawLine(_x1,_y1,_x2,_y1); DrawLine(_x2,_y1,_x2,_y2); DrawLine(_x2,_y2,_x1,_y2); DrawLine(_x2,_y1,_x1,_y1); } abstract void DrawLine( double x1, double y1, double x2, double y2); } class V1Rectangle : Rectangle { void override DrawLine( double x1, double y1, double x2, double y2) { DP1.draw_a_line( x1,y1,x2,y2); } } class V2Rectangle : Rectangle { void override DrawLine(double x1, double y1, double x2, double y2) { DP2.drawline( x1,x2,y1,y2); } } Get New Requirements  Told we must now handle Circles  We decide to handle it in a similar way  Make a V1Circle class and a V2Circle class  Decouple the client from the specific shapes by deriving them from a common base class Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 73
  • 76. Handling New Shape Class Handling New Shape Class Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 74
  • 77. C# Code Example abstract class Shape { public abstract void draw(); } abstract class Rectangle : Shape { private int _x1, _y1, _x2, _y2; public override void draw() { drawLine(_x1, _y1, _x2, _y1); drawLine(_x2, _y1, _x2, _y1); drawLine(_x2, _y2, _x1, _y2); drawLine(_x1, _y2, _x1, _y1); } abstract void drawLine( double x1, double y1, double x2, double y2); } } class V1Rectangle : Rectangle { public override void drawLine( double x1, double y1, double x2, double y2){ DP1.draw_a_line(x1,y1, x2, y2); } } class V2Rectangle : Rectangle { public override void drawLine( double x1, double y1, double x2, double y2){ DP2.drawline(x1, x2, y1, y2); } } abstract class Circle : Shape { private double _x, _y, _r; public override void draw () { drawArc( _x, _y, _r, 0, 360); } abstract void drawArc( double x, double y, double r, double a1, double a2); } class V1Circle : Circle { protected override void drawArc(double x, double y, double r, double a1, double a2){ DP1.draw_an_arc(x,y,r,a1,a2); } } class V2Circle : Circle { protected override void drawArc(double x, double y, double r, double a1, double a2){ DP2.drawarc(_r,_x,_y,a1,a2); } } Redundant Relationships Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 75
  • 78. Did We Resolve the Redundancy? Don't Trade One Redundancy for Another Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 76
  • 79. Problems with this Approach  Doesn’t scale well – If we add another type of Shape, we have 6 implementations – Number of implementations will equal # types of Shapes times # of drawing programs  Redundant – Clearly accessing each of the drawing programs across the different types of Shapes will involve duplication or require greater modularization – There will be many redundancies between V1Rectangle and V2Rectangle, etc…  Static – Must make new objects when any issue varies at runtime Intent Makes Sense Now  *GoF Intent: De-couple an abstraction from its implementation so that the two can vary independently  Abstraction: The entity, what something “is”. In this case – Shape  Implementation: What something “does”. In this case, the drawing behavior – Drawing *Design Patterns, Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 77
  • 80. Conceptual Point!  Many people say: – We use patterns to solve problems  This is sometimes true, but it’s much more useful to consider this: – Patterns are in the problems themselves – We just need a way to see them Seeing the Pattern in the Problem  Note that we can see that the Bridge pattern potentially applies without knowing anything about the details  …but what if we didn’t?  Could we discover it in the problem itself? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 78
  • 81. Discovering the Bridge Pattern  We use the following approach to discover the Bridge pattern 1. Find what is common in the problem domain 2. Define an abstraction to represent each common concept 3. Determine the nature of the variations, and create concrete entities  Lastly: – Observe how these abstractions relate to each other We Have the Following Commonalities  Our Shape class represents our commonality of   abstraction. It represents a varying entity. We also have a behavioral implementation which varies CVA separates these issues into is-a relationships Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 79
  • 82. Derive Variations Determine Remaining Relationships Which Way? Don't want them down here: "Design to Interfaces” Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 80
  • 83. Use Qualities to Define Relationship  Find different ways these CVA structures can work together: – Shapes use drawing programs to draw themselves – Client gives drawing program a shape to draw – A Manager coordinates them both  Whichever has better qualities is what we want (whether it happens to be a pattern or not)  New patterns can be discovered in this way Scoring Shapes use DP DP given Shape 3rd Module Loose Coupling Strong Cohesion No Redundancy Encapsulation Testable Focus Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 81
  • 84. Shapes Using Drawing Programs Drawing Programs Using Shapes Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 82
  • 85. Control Program Using Shapes Scoring Shapes use DP DP given Shape 3rd Module Loose Coupling Yes DPs coupled to Shapes Module coupled to Shapes Strong Cohesion Yes DPs concerned with Shapes Weak: Shape and Draw stuff No Redundancy Yes Knowledge of shapes duplicated in DPs Knowledge of shapes duplicated in CP Encapsulation implementation and type implementation only implementation only Testable Assertive Focus N+M N*M N+M Yes No No Yes Shapes spread out a Yes little Shapes using DPs wins! ~3 Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 83
  • 86. Add the Relationship The Adapter Pattern Why Didn't We Need Adapters Here? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 84
  • 87. Patterns as Operators "Each pattern is an operator which differentiates space: that is, it creates distinctions where no distinction was before “ Christopher Alexander, The Timeless Way of Building Illustrating the Separation Abstraction Implementation Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 85
  • 88. C# Example Implementation class Client { abstract class Shape { private Drawing _dp; public static void Main (String argv[]) { Shape s1; Shape s2; Drawing dp; Shape (Drawing dp) { _dp= dp; } abstract void draw (); // See comments below to see what // gets returned dp= Factory.getDP(); s1= Factory.getShape(dp); dp= Factory.getDP(); s2= Factory.getShape(dp); protected void drawLine ( double x1, double y1, double x2, double y2) { _dp.drawLine( x1, y1, x2, y2); } s1.draw(); s2.draw(); protected void drawArc ( double x, double y, double radius, double fromAngle, double toAngle){ _dp.drawArc( x,y,radius, fromAngle, toAngle); } } } // Factory: // first call: getDP returns V1Drawing // first call: getShape returns // new Rectangle(dp,1,1,2,2); } // second call: getDP returns V2Drawing // second call: getShape returns // new Circle( dp,2,2,4); C# Example Continued class Rectangle : Shape { Rectangle : base(dp) (Drawing dp, double x1, double y1, double x2, double y2) { _x1= x1; _y1= y1; _x2= x2; _y2= y2; } public override void draw () { drawLine(_x1, _y1, _x2, _y1); drawLine(_x2, _y1, _x2, _y2); drawLine(_x2, _y2, _x2, _y1); drawLine(_x2, _y1, _x1, _y1); } } class Circle : Shape { Circle : base(dp)(Drawing dp, double x, double y, double radius) { _x= x; _y= y; _radius= radius; } public override void draw () { drawArc(_x,_y,_radius, 0, 360); } } abstract class Drawing { abstract void drawLine ( double x1, double y1, double x2, double y2); abstract void drawArc( double x,double y,double radius, double fromAngle, double toAngle); } class V1Drawing : Drawing { public override void drawLine ( double x1, double y1, double x2, double y2) { DP1.draw_a_line( x1, y1, x2, y2); } public override void drawArc ( double x, double y, double radius, double fromAngle, double toAngle) { DP1.draw_an_arc( x, y,radius, fromAngle,toAngle); } } Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 86
  • 89. C# Example Continued class V2Drawing : Drawing { public override void drawLine ( double x1, double y1, double x2, double y2) { DP2.drawline( x1, x2, y1, y2); } public override void drawArc ( double x, double y, double radius, double fromAngle, double toAngle) { DP2.drawarc(radius, x, y, fromAngle, toAngle); } } class DP1 { static void draw_a_line ( double x1, double y1, double x2, double y2) { // draw_a_line implementation given to us } static void draw_an_arc( double x, double y, double radius, double from_angle, double to_angle) { // draw_an_arc implementation given to us } } class DP2 { static void drawline ( double x1, double y1, double x2, double y2) { // drawline implementation given to us } static void drawarc( double radius, double x, double y, double fromangle, double toangle) { // drawarc implementation given to us } } Canonical Bridge Pattern Abstraction + operation() Concrete1 Implementation + opImp1() + opImp2() Concrete2 ImpA operation() { imp.opImp1() } operation() { imp.opImp2() } ImpB + opImp1() + opImp2() + opImp1() + opImp2() Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 87
  • 90. Bridge Pattern and the GoF Advice (1) Find what varies and (2) Encapsulate it. Use inheritance to categorize. (3) Design to Interfaces (3) (2) (2) (1) (1) (1) (1) Another Way to Think of Bridge  Consider the following: – The cost of having a common interface for the implementation – The benefits of separating the issues, testability, cohesion, clarity, extensibility, etc…  If the benefits are greater than the cost, use it  If not, the pattern tells you “Don’t use me!” Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 88
  • 91. The Two Designs… Bridge Strategy Comparing Strategy and Bridge Strategy Bridge Contains variation of behavior? Yes Yes Behaviors are isolated Yes No, dependant Risk of Interface Bloat No Yes Open-Closed to… New behavior How many variations are encapsulated 1 New entity, behavior, way of using behaviors 3 Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 89
  • 92. The Façade copyright © 2010 Net Objectives Inc. The Façade Pattern  We want to use a sub-set of the functionality of a complex system, or to simplify its interface, or to improve how it is used, or to provide OO access to a non-OO system  GoF Intent*: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use *Design Patterns, Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 90
  • 93. 8’ of Manuals: One Complex System Using a Complex System  If you were in a group of developers that had to use parts of a complex system, would you: A. have everyone learn how to use it? B. draw straws where the loser had to learn it and make a set of classes for you to use?  If you picked B, what that person created would be a Façade Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 91
  • 94. Façade Insulating Ourselves From the Complex System Standard Façade vs. Encapsulating Facade  The Façade normally is used to simplify the use of a complex system  However, clients may use it or not -- they may use the complex system directly too  An Encapsulating Façade restricts access to the complex system -- clients must use the Façade  This has advantages Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 92
  • 95. Advantages of the Encapsulating Façade  The Façade itself can be varied, using polymorphism, to allow for: – Testing (Dummy Façade) – Marketing/Presentations - Demonstration Façade is used to simulate a remote system – Training – "Demo" versions of commercial software – etc… Comparing Façade With Adapter Client Pre-Existing ? which pattern? Façade Adapter Pre-Existing, or Foreign classes? Yes Yes Is there an existing interface we must adhere to? No Yes Are we trying to enable polymorphism? No Usually Are we creating a new interface for simplification? Yes No Yes, Façades tend to be large Not usually Is statefullness a concern? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 93
  • 96. Adapter and Façade Mean: Defer Having to Worry About Your Interface  You can use the Adapter and Façade patterns to make  the interfaces of classes you have been given to be exactly the way you want them to This is an example of design by context. First figure out what you want, then adapt (or simplify with a Facade) the interface to how you want it The Thought Process of Patterns Programming by Intention copyright © 2010 Net Objectives Inc. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 94
  • 97. C#/Java/… Programming by Intention "Sergeant" Method public void printReport (String CustomerID) { Employee[] emps = getEmployees(CustomerID); if(needsSorting(emps)) sortEmployees(emps); printHeader(CustomerID); printFormattedEmployees(emps); printFooter(CustomerID); "Private"* paginate(); Methods } *Note: These methods may not be literally private, as we may need to make some of them public or protected for testing. But we treat them as private from client objects, to limit coupling. The Thought Process of Patterns Shalloway’s Law copyright © 2010 Net Objectives Inc. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 95
  • 98. Shalloway’s Law If ‘N’ things need to change and ‘N>1’, Shalloway will find at most ‘N-1’ of these things Shalloway’s Principle Avoid situations where Shalloway’s Law Applies Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 96
  • 99. The Thought Process of Patterns Encapsulate that! copyright © 2010 Net Objectives Inc. Our Situation  We have multiple processors in a real-time environment.  We know there will be a performance problem. We just don’t know where / how.  What can we do? Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 97
  • 100. Our Options 1. Figure out where / how the performance problem will 2. 3. show up. Just use what appears best at first and fix it later if it becomes clear later that we need something else Use Scott Bain’s magic consultant card ~3 Scott Bain’s Magic Consultant Card  Scott, a Net Objectives’ Design Patterns Instructor, has a magic card that tells you how to solve design problems  It requires, however, that you explicitly and concisely state what your problem is  Fortunately, we know what our problem is: – We do not know the nature of the collection we need ~3 Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 98
  • 101. Instructions for Using the Magic Consultant Card 1. Hold magic card face down in front of you 2. State aloud three times what your problem is 3. Flip the card over 4. Read the card ~3 Using the Magic Design Card "Encapsulate That" ~3 Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 99
  • 102. Limits of the Magic Design Card and Where Design Patterns Help  First the good news – the magic card is always right!  Now the bad news – it doesn’t tell you how to do what it tells you to do!  That’s where design patterns come in – Encapsulate what varies ~3 Summary • Attend to code qualities • Gang of Four Advice – Design to interfaces – Delegate – Encapsulate what varies • Use testability as a design • • • • tool Program by intention Encapsulate Shalloway’s Principle Patterns hide variation Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 100
  • 103. Net Objectives’ Webinars Business & Agile Webinar Series – April – December 2013  An Introduction to Agile from a Business / Executive Point of View  Agile Implementations: Overviews of Scrum, Kanban, and Scrumban  How to Start an Agile Implementation  Team Kanban: Manifesting Lean at the Team Level  Enhancing and Extending Scrum With Lean  Patterns of Scaling Agile Across Teams  Patterns of Scaling Agile Across an Enterprise (will discuss the Scaled Agile Framework as well as our own Lean-Agile Roadmap  The Net Objectives Enterprise Agility Roadmap: Patterns of Successful Lean-Agile Adoption Technical Agility Series  Technical Agility: What Design Patterns Were Made For  Emergent Design: The Practical Application of Design Patterns in the Agile World  Acceptance Test-Driven Development: An Essential Practice That Saves More Time Than It Takes  Sustainable Test-Driven Development: How to Have TDD Improve Your Designs and Tests Without Slowing You Down See www.netobjectives.com/events to learn more Register at www.netobjectives.com/register for slides & more _s Thank You!     Register at www.netobjectives.com/register See www.netobjectives.com/resources Contact me at alshall@netobjectives.com Twitter tag @alshalloway copyright © 2010 Net Objectives Inc. Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 101
  • 104. Q U E S T I O N S ? Lean for Executives Product Portfolio Management Business Product Owner Scaled Agile Framework Business ASSESSMENTS CONSULTING T RAINING COACHING Lean Enterprise Manage ment Team technical For more info on free resources see: www.netobjectives.com/resources process Lean-Agile Kanban / Scrum ATDD / TDD / Design Patterns Lean Management Project Management Copyright © 2007 Net Objectives. All Rights Reserved. 12 April 2013 102

×