Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Common ASP.NET       Design Patterns       Steve Smith       @ardalis | ardalis.com       Telerikhttp://flic.kr/p/4MEeVn
Design Patternshttp://flic.kr/p/8XgqKu
Stages of LearningStage Zero - IgnoranceStage One - AwakeningStage Two - OverzealousStage Three – Masteryhttp://flic.kr/p/...
Languagehttp://flic.kr/p/6UpMt9
Actual Usage Twitter Poll in 2011 w/342 responses    http://twtpoll.com/r/t7jzrx                                   Votes...
Common Design Patterns0.Singleton1.Strategy2.Repository3.Proxy        (Of course there are many others!)4.Command5.Factory
(Singleton)
Singleton: Intent Ensure a class has only one instance Make the class itself responsible for  keeping track of its sole ...
Singleton Structure (not thread-safe)
How Singleton Is Used Call methods on  Instance directly Assign variables to  Instance Pass as Parameter
Singleton Structure(thread-safe and fast) Source: http://csharpindepth.com/Articles/General/Singleton.aspx
Singleton Consequences The default implementation not thread-safe     Avoid in multi-threaded environments     Avoid in...
Managing Object Lifetime Using an IOC Container
Strategyhttp://flic.kr/p/6spkwo
Strategy: Intent Encapsulate a family of related algorithms Let the algorithm vary and evolve independently from the  cl...
Strategy : Structure
Strategy : Common Usage Dependency Inversion and Dependency Injection Decouple class dependencies and responsibilitiesRe...
Hidden Dependencies Classes should declare their dependencies via their  constructor Avoid hidden dependencies    Anyth...
“New is Glue”                            “new” creates tight coupling                            between classesBe conscio...
Repository
Data Access EvolutionNo separation of concerns:                       Compile Time                                        ...
Data Access : Helper           Classes                     Compile Time Calls to data made through a  utility            ...
What’s Missing?                           Compile Time            Abstraction!                                 Runtime No...
Repository A Data Access Pattern Separates persistence responsibility from business classes Enables    Single Responsi...
Repository - Example
Repository - Example                                        (1)                                        Create/extend an in...
Where do Repositories Live? Place interfaces in Core    Core includes Model classes and most business logic    Core has...
Proxy
Proxy A class that controls access to another Implemented via subclass or via delegation using a  common interface Freq...
Proxy - Structure
Adding Caching to a              Repository Caching is frequently added to query methods in repositories Caching logic i...
Proxy – CachedRepository Implementation
Implementing with IOC// Strategy Pattern with Proxy Pattern (using composition)x.For<IAlbumRepository>().Use<CachedAlbumRe...
Commandhttp://flic.kr/p/5Yb5i
Command Represent an action as an object Decouple performing the action  from the client that is issuing the  command C...
Command
Command : Usage Great for representing state transitions (the arrows below)                                      Pending ...
Factoryhttp://flic.kr/p/vGpC2
Factory: Intent Separate object creation from the decision of which object to  create Defer creation of objects    Only...
Practice PDD Pain Driven DevelopmentIf it’s causing pain, fix it.
Design Patterns in ActionCODE WALKTHROUGH
A Tale from theREAL WORLD
References   Design Patterns, http://amzn.to/95q9ux   Design Patterns Explained, http://amzn.to/cr8Vxb   Design Pattern...
Summary Design Patterns can be used during  refactoring or initial design to improve code  quality Become comfortable wi...
Upcoming SlideShare
Loading in …5
×

Common ASP.NET Design Patterns - Telerik India DevCon 2013

9,747 views

Published on

An overview of several design patterns that are useful when developing ASP.NET applications.

Published in: Technology
  • Be the first to comment

Common ASP.NET Design Patterns - Telerik India DevCon 2013

  1. 1. Common ASP.NET Design Patterns Steve Smith @ardalis | ardalis.com Telerikhttp://flic.kr/p/4MEeVn
  2. 2. Design Patternshttp://flic.kr/p/8XgqKu
  3. 3. Stages of LearningStage Zero - IgnoranceStage One - AwakeningStage Two - OverzealousStage Three – Masteryhttp://flic.kr/p/6StgW5
  4. 4. Languagehttp://flic.kr/p/6UpMt9
  5. 5. Actual Usage Twitter Poll in 2011 w/342 responses  http://twtpoll.com/r/t7jzrx Votes 250 200 150 100 50 Votes 0
  6. 6. Common Design Patterns0.Singleton1.Strategy2.Repository3.Proxy (Of course there are many others!)4.Command5.Factory
  7. 7. (Singleton)
  8. 8. Singleton: Intent Ensure a class has only one instance Make the class itself responsible for keeping track of its sole instance “There can be only one”
  9. 9. Singleton Structure (not thread-safe)
  10. 10. How Singleton Is Used Call methods on Instance directly Assign variables to Instance Pass as Parameter
  11. 11. Singleton Structure(thread-safe and fast) Source: http://csharpindepth.com/Articles/General/Singleton.aspx
  12. 12. Singleton Consequences The default implementation not thread-safe  Avoid in multi-threaded environments  Avoid in web server scenarios (e.g. ASP.NET) Singletons introduce tight coupling among collaborating classes Shameless Plug: But why would you Telerik JustMock can be intentionally write code Singletons are notoriously difficult to test usedcan mocktest with you to only and test  Commonly regarded as an anti-pattern certainSingletons tools? premium Violate the Single Responsibility Principle  Class is responsible for managing its instances as well as whatever it does Using an IOC Container it is straightforward to avoid the coupling and testability issues
  13. 13. Managing Object Lifetime Using an IOC Container
  14. 14. Strategyhttp://flic.kr/p/6spkwo
  15. 15. Strategy: Intent Encapsulate a family of related algorithms Let the algorithm vary and evolve independently from the class(es) that use it Allow a class to maintain a single purpose  Single Responsibility Principle (SRP)  Also enables Open/Closed Principle (OCP)  Learn more about SRP and OCP here:  http://pluralsight.com/training/Courses/TableOfContents/principles-oo-design
  16. 16. Strategy : Structure
  17. 17. Strategy : Common Usage Dependency Inversion and Dependency Injection Decouple class dependencies and responsibilitiesRefactoring Steps Create interfaces for each responsibility Inject the implementation of the interface via the constructor Move the implementation to a new class that implements the interface
  18. 18. Hidden Dependencies Classes should declare their dependencies via their constructor Avoid hidden dependencies  Anything the class needs but which is not passed into constructor Avoid making non-stateless static calls Avoid directly instantiating classes (except those with no dependencies, like strings)  Instead, move these calls to an interface, and call a local instance of the interface
  19. 19. “New is Glue” “new” creates tight coupling between classesBe conscious of theconsequences of using“new”If you need loosecoupling, replace“new” with StrategyPatternhttp://flic.kr/p/aN4Zv
  20. 20. Repository
  21. 21. Data Access EvolutionNo separation of concerns: Compile Time Runtime Data access logic baked directly into UI  ASP.NET Data Source Controls  Classic ASP scripts User Interface Data access logic in UI layer via codebehind  ASP.NET Page_Load event  ASP.NET Button_Click event Database
  22. 22. Data Access : Helper Classes Compile Time Calls to data made through a utility Runtime Example: Data Access Application Block (SqlHelper) User Interface Logic may still live in UI layer Helper Class Or a Business Logic Layer may make calls to a Data Access Layer which might then call the helper Database
  23. 23. What’s Missing? Compile Time Abstraction! Runtime No way to abstract away data access User Interface Tight coupling Leads to Big Ball of Mud Core Infrastructure system IFooRepository SqlFooRepository Solution:  Depend on interfaces, not concrete implementations  What should we call such Database interfaces? Repositories!
  24. 24. Repository A Data Access Pattern Separates persistence responsibility from business classes Enables  Single Responsibility Principle  Separation of Concerns  Testability Frequently Separate Interfaces for Each Entity in Application  E.g. CustomerRepository, OrderRepository, etc.  Or using Generics: IRepository<TEntity> May also organize Repositories based on  Reads vs. Writes  Bounded Contexts
  25. 25. Repository - Example
  26. 26. Repository - Example (1) Create/extend an interface to represent the data access you need (2) Copy the implementation from your class into a new class implementing this interface.(3)Inject the interface using theStrategy Pattern. Use the local fieldof this interface type in place ofprevious implementation code.
  27. 27. Where do Repositories Live? Place interfaces in Core  Core includes Model classes and most business logic  Core has no dependencies (ideally) Place implementation in Infrastructure  Infrastructure references Core UI layer references both Core and Infrastructure  Responsible for creating object graph, either manually or via an IOC Container
  28. 28. Proxy
  29. 29. Proxy A class that controls access to another Implemented via subclass or via delegation using a common interface Frequent use cases:  Remote Proxy for web services / network calls  Lazy loading implementations  Security / access control
  30. 30. Proxy - Structure
  31. 31. Adding Caching to a Repository Caching is frequently added to query methods in repositories Caching logic is a separate concern and should live in a separate class from the main data access logic Proxy pattern provides a straightforward means to control access to the “real” data, versus the cache
  32. 32. Proxy – CachedRepository Implementation
  33. 33. Implementing with IOC// Strategy Pattern with Proxy Pattern (using composition)x.For<IAlbumRepository>().Use<CachedAlbumRepository>() .Ctor<IAlbumRepository>().Is<EfAlbumRepository>();
  34. 34. Commandhttp://flic.kr/p/5Yb5i
  35. 35. Command Represent an action as an object Decouple performing the action from the client that is issuing the command Common scenarios:  Delayed execution  Logging activity  Enabling Undo / Revoke Transaction functionality
  36. 36. Command
  37. 37. Command : Usage Great for representing state transitions (the arrows below) Pending Archived Published
  38. 38. Factoryhttp://flic.kr/p/vGpC2
  39. 39. Factory: Intent Separate object creation from the decision of which object to create Defer creation of objects  Only create them if and when needed Add new classes and functionality without breaking client code  Only factory needs to know about new types available Store possible objects to create outside of program  Configuration  Persistent Storage  Plug-in assemblies
  40. 40. Practice PDD Pain Driven DevelopmentIf it’s causing pain, fix it.
  41. 41. Design Patterns in ActionCODE WALKTHROUGH
  42. 42. A Tale from theREAL WORLD
  43. 43. References Design Patterns, http://amzn.to/95q9ux Design Patterns Explained, http://amzn.to/cr8Vxb Design Patterns in C#, http://amzn.to/bqJgdU Head First Design Patterns, http://amzn.to/aA4RS6Pluralsight Resources N-Tier Application Design in C# http://bit.ly/Msrwig Design Patterns Library http://bit.ly/vyPEgK SOLID Principles of OO Design http://bit.ly/OWF4la My Blog  http://ardalis.com
  44. 44. Summary Design Patterns can be used during refactoring or initial design to improve code quality Become comfortable with a number of design patterns, but focus on the most common ones Use design patterns to address pain in your design, such as tight coupling or excessive repetition Design patterns can be combined in powerful ways, such as Strategy-Proxy-Repository

×