An Introduction to Design Patterns. What is a design pattern? Why should you care? What it the power of design patterns? How do design patterns tie into object oriented programming? If I'm using objects in my code, isn't that object oriented programming? (The answer is not necessarily!) We'll talk about why you should know common design patterns, why they are powerful and how to make sure you're leveraging object oriented programming principles, not just "programming with objects".
Power of Patterns OR More Than Programming with Objects
1. Power of PatternsORMore Than Programming with Objects Intro to Design Patterns Mike Clement @mdclement mike@softwareontheside.com http://blog.softwareontheside.com Utah Code Camp Fall 2011
3. “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to the problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice.” -Christopher Alexander
4. A Pattern is a solution to a problem in a context Context – recurring situation Problem – goal and constraints Solution – general design to resolve the problem If it only happened once, it’s not a pattern
5. Why should I care About Patterns? The question of the day!
8. Power of a Pattern Language A shared vocabulary Powerful Say more with less Stay “in the design” longer Turbo charge the team Gets new hires up to speed
9. From Architecture to Software 1987 – Kent Beck and Ward Cunningham presented at OOPSLA 1994 – GoF book published
10. GOF Pattern Template Pattern Name Classification Intent Also Known As Motivation Applicability Structure Participants Collaborations Consequences Implementation Sample Code Known Uses Related Patterns
11. GoF Pattern Catalog Creational Patterns Abstract Factory Creates an instance of several families of classes Builder Separates object construction from its representation Factory Method Creates an instance of several derived classes Prototype A fully initialized instance to be copied or cloned Singleton A class of which only a single instance can exist Structural Patterns Adapter Match interfaces of different classes Bridge Separates an object’s interface from its implementation Composite A tree structure of simple and composite objects Decorator Add responsibilities to objects dynamically Facade A single class that represents an entire subsystem Flyweight A fine-grained instance used for efficient sharing Proxy An object representing another object Behavioral Patterns Chain of Resp. A way of passing a request between a chain of objects Command Encapsulate a command request as an object Interpreter A way to include language elements in a program Iterator Sequentially access the elements of a collection Mediator Defines simplified communication between classes Memento Capture and restore an object's internal state Observer A way of notifying change to a number of classes State Alter an object's behavior when its state changes Strategy Encapsulates an algorithm inside a class Template Method Defer the exact steps of an algorithm to a subclass Visitor Defines a new operation to a class without change
13. We need some code that… Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically
14. Observer Pattern Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically Also Known As: Publish-Subscribe
31. OO Principles Encapsulate what varies. Favor composition over inheritance. Program to interfaces, not implementations. Strive for loosely coupled designs between objects that interact. Open for extension but closed for modification. Depend on abstractions. Only talk to your friends. Don't call us, we'll call you. A class should have only one reason to change.
33. Anti-Patterns Tells you how to go from a problem to a BAD solution. Why the bad solution is unattractive Why in the long term it’s bad Suggests other patterns for a good solution
34. Catalog… Big Ball of Mud Gold Plating Interface Bloat God Object Coding by Exception Copy and Paste Golden Hammer Cargo Cult Analysis Paralysis Design by Committee Vendor Lock-in Groupthink Mushroom Management
35.
36.
37. Share the Vocabulary In design meetings With other developers In architecture documentation In code comments and naming conventions To groups of interested developers
38. Learning more… I really like this one… some people find it annoying. Puts Design Patterns in the context of OOP. Great reference. Definitive resource. Put me to sleep the first couple times I tried to read it though.
39. My Contact Info @mdclement mike@softwareontheside.com http://blog.softwareontheside.com Utah Software Craftsmanship Group https://groups.google.com/forum/#!forum/ut-software-craftsmanship @utahsc
Editor's Notes
"Each solution is stated in such a way that it gives the essential field of relationships needed to solve the problem, but in a very general and abstract way - so that you can solve the problem for yourself, in your own way, by adapting it to your preferences, and the local conditions at the place where you are making it.“Includes patterns for “problems” such asHomes“Couple’s Realm”“Farmhouse Kitchen”“Bulk Storage”Offices Space“Communal Eating”“A Place to Wait”Communities“Ring Roads”“Web of Shopping”“Sacred Sites”“Night Life”“Household Mix”
When you say “kitchen” you get all those other descriptors for free. Instead of detailing everything, you can focus on exceptions to the pattern.
From Head First Design Patterns p28A shared vocabularyPowerful – communicating qualities, characteristics and constraintsSay more with lessStay “in the design” longer – avoids getting prematurely into implementation detailsTurbo charge the team – team moves more quickly with less room for misunderstandingGets new hires up to speed – easily allows new hires (college or industry)to get up to speed with defined patterns
1987 is when Kent Beck and Ward Cunningham first introduced the concept to software. Took another few years before the GoF book was published and then from there it’s exploded.
Sample CodeUse of sample code is a little bit controversial because of the previous statements. GoF writers decided that the usefulness of having something concrete outweighed the need for “purity” in their pattern catalog. Even class diagrams can be too prescriptive which we’ll see later.ConsequencesBoth positive and negative. Sometimes a pattern’s effects are not entirely positive.
Creational – where objects come from, instantiationBehavioral – interaction and responsibilityStructural – composing classes/object into larger structures
Instead of this, I could simply say… let’s use the…
Often as part of a pattern definition we’ll have a class diagram to help describe how the pattern *could* be implemented. Remember Alexander said a pattern means that we can “use this solution a million times over, without ever doing it the same way twice”
Raises the question, Is a class diagram too much for pattern definition?.NET alternatives to this class structure?
Those that build pattern catalogs aren’t “creators” but are discoverers. They “see” the pattern and catalog it.
Two of the OO Basics that usually go hand in hand are Inheritance and Polymorphism. If you don’t remember, the other two are Abstraction and Encapsulation. (these can change depending on who is defining… but regardless…)What is a “classic” use of inheritance and polymorphism? What’s the first think you coded up in intro to programming that used inheritance?Shapes, animalsWe’re going to use ducks…
“Classic” use of inheritance… different types of somethingCurrently we just have to display the ducks so this is okay. But…
What if we add “fly()”? Here we add it to the base class and all the subclasses fly fine but…
What seemed like a great use of inheritance for reuse hasn’t worked out so well for maintenanceRemember, that writing code “fast” now isn’t usually the main goal. We need to write code that can be easily maintained.By maintained I mean any future modification, including debugging and modifications BEFORE release of the product.
Using the Java “able” interface convention.No inappropriate behaviors but now behavior code is duplicated.We traded one maintenance problem for another!
Instead of having the behavior embedded in the classes, we’re going to encapsulate them elsewhere. This way they are centralized (not duplicated) and
Those that build pattern catalogs aren’t “creators” but are discoverers. They “see” the pattern and catalog it.
Application of OO Principles will usually drive us to a well known good pattern or variation of a pattern.We took Encapsulate what varies combined with Program to interfaces not implementations and we ended up with the Strategy Pattern.
Architectural – already talked about itApplication – System level, multi-tierDomain – concurrent or real-time systems, maybe even domains like accountingBusiness Processes – interaction between businesses, within businesses, communicate decisions You expect order confirmation emailOrganizational – human organizations (how teams are structured, interact with other teams)AJAX or UI in generalWidgets – what do you expect them to do?Visual effects – highlighting changes
Ineffective and/or counterproductive practices.Why Anti-patterns?By formally describing repeated mistakes, one can recognize the forces that lead to their repetition and learn how others have refactored themselves out of these broken patterns.
Big ball of mud: A system with no recognizable structureGold plating: Continuing to work on a task or project well past the point at which extra effort is adding valueInterface bloat: Making an interface so powerful that it is extremely difficult to implementGod object: Concentrating too many functions in a single part of the design (class)Coding by exception: Adding new code to handle each special case as it is recognizedCopy and paste programming: Copying (and modifying) existing code rather than creating generic solutionsGolden hammer: Assuming that a favorite solution is universally applicableCargo cult programming: Using patterns and methods without understanding whyAnalysis paralysis: Devoting disproportionate effort to the analysis phase of a projectDesign by committee: The result of having many contributors to a design, but no unifying visionVendor lock-in: Making a system excessively dependent on an externally supplied componentGroupthink: During groupthink, members of the group avoid promoting viewpoints outside the comfort zone of consensus thinkingMushroom management: Keeping employees uninformed and misinformed (kept in the dark and fed manure), let to stew, and finally canned.
Use it or it’s not usefulCan use the brownbag sessions in the future to present different design patterns/pattern languages or catalogs