Introduction to Object-Oriented Design Patterns Presentation for IPMA Forum 2004 Glenn Briskin – Director of Consulting Services – Sierra Systems Inc. Nick Malik – Development Lead – Microsoft Sierra Corporate Profile Publicly traded on TSX (SSG) – Founded in 1966 – 2002/03 Revenue of $150 million 750+ consultants (Average of 11 yrs in IT industry) – 10% having professional designations – 15% with graduate degrees – 25% with technical certifications 2 Washington State Locations – 16 offices throughout North America Microsoft Gold Certified Partner eGovernment Practice eProcurement Insurance and Benefits Claims Management K-12 and Higher Education – Human Resources – Payroll – Finance – Student Records – Data Management Lands, Title and Deeds Management Legislative Licensing and Permitting Municipal and Physical Infrastructure Management Natural Resources Management Public Sector Administration Safety, Quality, Regulatory and other Inspection Services Tax and Revenue Management Agenda What are design patterns? Architectural vs. Design patterns An example problem Design patterns as a catalyst for change How to learn design patterns References and Acknowledgements What is a Design Pattern? A solutions to a commonly occurring design problem Help create flexible and reusable designs Larger scope than a single class or algorithm Describes the circumstances in which the pattern is applicable Describes the consequences and trade-offs of using the pattern within a larger design Language Independent Architectural vs. Design Patterns Architectural patterns address problems of – – – – Distributed functionality and system partitioning Protocols and Interfaces Scalability, Reliability, Security Leverages the “Distributed system” Design patterns address problems of – Maintainability, code reuse, and frameworks – Abstraction and algorithm hiding – Leverages the “Object oriented language” What problem does DP solve? Good designs can cope with change – Underlying technologies change – Business goals change – User expectations change OOP gives us the tools to cope with change: – Encapsulation – Inheritance – Polymorphism Having tools = good. Using them well = better. An Example Problem In the beginning, you get the following requirement: The regional sales entry system must send data, in batches, to the accounting package (Microsoft Great Plains Accounts Receivable). You create the OrderCollector class. Open a GP connection Create the batch envelope Open a DB connection Loop through DB to find transactions to submit Submit each transaction to GP Submit the batch to GP Close the DB connection Close the GP connection OrderCollector + CreateAndSubmitARBatch(String) : bool GreatPlainsInterface + + + + SubmitTransToBatch(int, String) : bool CreateBatchEnvelope(int) : void SubmitBatchToAR(String, String) : bool OpenGPConnection(String) : String And now the requirements change Good news: our departmental application is being picked up by the manufacturing division in Florida. Bad news: they use Solomon for their accounting package. Fix the code to use Solomon as well as Microsoft Great Plains. The interaction is quite different. You have to change the code that calls the accounting interface. The new diagram If Great Plains, call GP_Batch else if Solomon call Solomon_Batch end if GreatPlainsInterface OrderCollector + + + CreateAndSubmitARBatch(String) : bool GP_Batch() : void Solomon_Batch() : void + + + + SubmitTransToBatch(int, String) : bool CreateBatchEnvelope(int) : void SubmitBatchToAR(String, String) : bool OpenGPConnection(String) : String SolomonInterface + + + + + + OpenSolomonConnection() : int CreateCompanyEnvelope() : int CreateBatchEnvelope() : int SubmitTransToBatch() : int SubmitCompanyFileToAR() : int CloseBatchEnvelope() : int The problem with the solution The code to call the Microsoft Great Plains solution is similar to the code that calls the Solomon solution. Business rules specific to the task of “send something to accounting” are mixed in with business rules for “send data to the specific package.” Therefore: if another accounting package comes in, say Oracle, you’d have to do it again. The interfaces are fairly different… inheritance doesn’t appear to help. Apply the Adapter pattern According to GoF, Adapter “converts the interface of a class into another interface clients expect.” In this example, we use one variation of the Adapter pattern called the “pluggable adapter using abstract operations” (see p.144 of GoF) The pattern looks like this: Adaptee Target Client +* Request() : void + SpecificRequest() : void Adapter + Request() : void adaptee->SpecificRequest() A better OO solution AbstractAdapter OrderCollector + +* +* +* +* CreateAndSubmitARBatch(String) : bool InitializeConnection() : void AddTransactionToSet() : void SubmitTransactionSet() : void TerminateConnection() : void GreatPlainsInterface GPAdapter Create Adapter Object Call InitializeConnection Get DB Records For each correct record <business rules> Call AddTransactionToSet <business rules> Call SubmitTransactionSet Call TerminateConnection + + + + + + + + InitializeConnection() : void AddTransactionToSet() : void SubmitTransactionSet() : void TerminateConnection() : void SolomonAdapter + + + + InitializeConnection() : void AddTransactionToSet() : void SubmitTransactionSet() : void TerminateConnection() : void SubmitTransToBatch(int, String) : bool CreateBatchEnvelope(int) : void SubmitBatchToAR(String, String) : bool OpenGPConnection(String) : String SolomonInterface + + + + + + OpenSolomonConnection() : int CreateCompanyEnvelope() : int CreateBatchEnvelope() : int SubmitTransToBatch() : int SubmitCompanyFileToAR() : int CloseBatchEnvelope() : int Better because Business rules are separate from technical rules. They are more readable and more testable. The business rules are implemented once and only once. This makes it easier to find and update business rules. If you add another accounting system, you only have to code another adapter. The business code already exists and can be reused (usually). So what’s the big deal? I could have done that with a code template! I’ve done that before on my own! Why call this a pattern? The power of Design Patterns does not come just from templates and bits of reusable code… It comes from a new way of thinking about objects. Patterns are the examples that lead us to make this leap. Some questions for you to ponder Are objects just “data with methods?” Does encapsulation mean the same thing as data hiding? Is inheritance best used to create “specialized” versions of a class? A different way of thinking Encapsulation = hide anything… not just data Objects as a “realized set of responsibilities” Abstract classes that define “common” capabilities of an object, with inheritance used to specify variations. A different way of programming Focus on what objects are supposed to do, not simply how to implement them. Consider what is variable in the design… then hide it. Put layers between things that independently change. Design Patterns = applied best practices in software design Proven methods for hiding things, not just data. “Commonality vs. Variability” lives at the heart of DP Benefits of using Design Patterns Establish a vocabulary – Allows teams to communicate at a higher lever – Reusing a technical solution allows you to focus on the business problem – Makes design documentation easier to understand Your code improves – More maintainable: Less coupling, greater cohesion – Internalize concepts of commonality vs. variability Your productivity improves – Why re-invent the wheel? How to learn Design Patterns Read the Gang-of-Four book. Better yet, Read the Shalloway book first, then read GoF. Better yet, join a Study Group, and study them both. Keep learning: – build a community of interest, and discuss them. – build a community of practice, and use them. Design Pattern Study Groups Joshua Kerievsky provides an excellent overview: http://www.industriallogic.com/papers/learning.html Learn the patterns in a specific order Meet frequently in small groups in a conducive space Socratic method – study a question and answer it using the material. Suggested Navigation (one order in which to learn the GoF patterns) l Factory Method u Strategy n Decorator n Composite u Iterator u Template Method l Abstract Factory l Builder l Singleton n Proxy n Adapter n Bridge u Mediator u Observer u Chain of Responsibility u Memento u Command l Prototype u State u Visitor n Flyweight l Creational u Interpreter nStructural n Facade u Behavioral AntiPatterns – what doesn’t work Software Development • The Blob • Lava Flow • Functional Decomposition • Poltergeists • Golden Hammer • Spaghetti Code • Cut-and-Paste programming Software Architecture • Stovepipe Enterprise • Stovepipe System • Vendor Lock-in • Architecture by Implication • Design by Committee • Reinvent the wheel Project Management • Analysis Paralysis • Death by Planning • Corncob • Irrational Management • Project Mismanagement Resources Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, and Vlissides Design Patterns Explained: A New Perspective on Object Oriented Design by Shalloway and Trott Anti-Patterns: Refactoring Software, Architectures and Projects in Crisis by Brown, Malveau, McCormick, and Mowbray Patterns Home Page – Vince Huston’s Patterns page – http://home.earthlink.net/~huston2/dp/patterns.html Portland Pattern Repository – http://hillside.net/patterns/patterns.html http://c2.com/ppr/ Microsoft’s Patterns and Practices – http://msdn.microsoft.com/practices/type/Patterns/enterprise/ Acknowledgements Significant portions of this presentation were adapted from original works by: – James C. Smith - Reflexive Entertainment, Inc. – Alan Shalloway – NetObjectives – Douglas Schmidt – University of California, Irvine – Joshua Kerievsky – Industrial Logic – Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (the Gang of Four) About Nick Malik: A development lead in Microsoft Business IT, Nick is an architect, author, speaker, trainer, designer, and all around problem solver. After 23 years of software development, he still loves to learn, discover, develop, and share what works. NMalik@Microsoft.com © 2002 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.