SlideShare una empresa de Scribd logo
1 de 44
Common ASP.NET
       Design Patterns


       Steve Smith
       @ardalis | ardalis.com
       Telerik
http://flic.kr/p/4MEeVn
Design Patterns




http://flic.kr/p/8XgqKu
Stages of Learning

Stage Zero - Ignorance

Stage One - Awakening

Stage Two - Overzealous

Stage Three – Mastery



http://flic.kr/p/6StgW5
Language




http://flic.kr/p/6UpMt9
Actual Usage
 Twitter Poll in 2011 w/342 responses
    http://twtpoll.com/r/t7jzrx
                                   Votes
     250
     200
     150
     100
       50
                                           Votes
        0
Common Design Patterns
0.Singleton
1.Strategy
2.Repository
3.Proxy        (Of course there are many others!)

4.Command
5.Factory
(Singleton)
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”
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 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
Managing Object Lifetime
 Using an IOC Container
Strategy




http://flic.kr/p/6spkwo
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
Strategy : Structure
Strategy : Common Usage
 Dependency Inversion and Dependency Injection

 Decouple class dependencies and responsibilities

Refactoring 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
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
“New is Glue”
                            “new” creates tight coupling
                            between classes


Be conscious of the
consequences of using
“new”

If you need loose
coupling, replace
“new” with Strategy
Pattern




http://flic.kr/p/aN4Zv
Repository
Data Access Evolution
No 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
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
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!
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
Repository - Example
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 the
Strategy Pattern. Use the local field
of this interface type in place of
previous implementation code.
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
Proxy
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
Proxy - Structure
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
Proxy – CachedRepository Implementation
Implementing with IOC
// Strategy Pattern with Proxy Pattern (using composition)
x.For<IAlbumRepository>().Use<CachedAlbumRepository>()
         .Ctor<IAlbumRepository>().Is<EfAlbumRepository>();
Command




http://flic.kr/p/5Yb5i
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
Command
Command : Usage
 Great for representing state transitions (the arrows below)



                                      Pending




                           Archived             Published
Factory




http://flic.kr/p/vGpC2
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
Practice PDD
 Pain

 Driven

 Development




If it’s causing pain, fix it.
Design Patterns in Action

CODE WALKTHROUGH
A Tale from the

REAL WORLD
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/aA4RS6

Pluralsight 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
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

Más contenido relacionado

La actualidad más candente

Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
 
How I Learned To Apply Design Patterns
How I Learned To Apply Design PatternsHow I Learned To Apply Design Patterns
How I Learned To Apply Design PatternsAndy Maleh
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesSteven Smith
 
Effective Java, Third Edition - Keepin' it Effective
Effective Java, Third Edition - Keepin' it EffectiveEffective Java, Third Edition - Keepin' it Effective
Effective Java, Third Edition - Keepin' it EffectiveC4Media
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfacesİbrahim Kürce
 
Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in androidJay Kumarr
 
Effective java
Effective javaEffective java
Effective javaEmprovise
 
Design Patterns in iOS
Design Patterns in iOSDesign Patterns in iOS
Design Patterns in iOSYi-Shou Chen
 
Aspect-Oriented Programming
Aspect-Oriented ProgrammingAspect-Oriented Programming
Aspect-Oriented ProgrammingAndrey Bratukhin
 
DIC To The Limit – deSymfonyDay, Barcelona 2014
DIC To The Limit – deSymfonyDay, Barcelona 2014DIC To The Limit – deSymfonyDay, Barcelona 2014
DIC To The Limit – deSymfonyDay, Barcelona 2014Ronny López
 
Solid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignSolid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignIrwansyah Irwansyah
 
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleP Heinonen
 
SOLID Software Principles with C#
SOLID Software Principles with C#SOLID Software Principles with C#
SOLID Software Principles with C#Ken Burkhardt
 
Open Closed Principle kata
Open Closed Principle kataOpen Closed Principle kata
Open Closed Principle kataPaul Blundell
 
Distributed Programming (RMI)
Distributed Programming (RMI)Distributed Programming (RMI)
Distributed Programming (RMI)Ravi Kant Sahu
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented ProgrammingRajesh Ganesan
 
The Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original VersionThe Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original VersionPhilip Schwarz
 

La actualidad más candente (20)

Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
How I Learned To Apply Design Patterns
How I Learned To Apply Design PatternsHow I Learned To Apply Design Patterns
How I Learned To Apply Design Patterns
 
AOP
AOPAOP
AOP
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID Principles
 
Effective Java, Third Edition - Keepin' it Effective
Effective Java, Third Edition - Keepin' it EffectiveEffective Java, Third Edition - Keepin' it Effective
Effective Java, Third Edition - Keepin' it Effective
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
 
Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in android
 
Effective java
Effective javaEffective java
Effective java
 
Design Patterns in iOS
Design Patterns in iOSDesign Patterns in iOS
Design Patterns in iOS
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Aspect-Oriented Programming
Aspect-Oriented ProgrammingAspect-Oriented Programming
Aspect-Oriented Programming
 
DIC To The Limit – deSymfonyDay, Barcelona 2014
DIC To The Limit – deSymfonyDay, Barcelona 2014DIC To The Limit – deSymfonyDay, Barcelona 2014
DIC To The Limit – deSymfonyDay, Barcelona 2014
 
Solid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignSolid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven Design
 
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
 
SOLID Software Principles with C#
SOLID Software Principles with C#SOLID Software Principles with C#
SOLID Software Principles with C#
 
Open Closed Principle kata
Open Closed Principle kataOpen Closed Principle kata
Open Closed Principle kata
 
Distributed Programming (RMI)
Distributed Programming (RMI)Distributed Programming (RMI)
Distributed Programming (RMI)
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
 
The Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original VersionThe Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original Version
 

Similar a Common ASP.NET Design Patterns - Telerik India DevCon 2013

Bartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsBartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsJason Townsend, MBA
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxdanhaley45372
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Elements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstElements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstEnea Gabriel
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShareyayao
 
System verilog important
System verilog importantSystem verilog important
System verilog importantelumalai7
 
Enterprise Library 2.0
Enterprise Library 2.0Enterprise Library 2.0
Enterprise Library 2.0Raju Permandla
 
.NET TECHNOLOGIES
.NET TECHNOLOGIES.NET TECHNOLOGIES
.NET TECHNOLOGIESProf Ansari
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa TouchEliah Nikans
 
Stateful mock servers to the rescue on REST ecosystems
Stateful mock servers to the rescue on REST ecosystemsStateful mock servers to the rescue on REST ecosystems
Stateful mock servers to the rescue on REST ecosystemsNuno Caneco
 
Evolution of Patterns
Evolution of PatternsEvolution of Patterns
Evolution of PatternsChris Eargle
 
ActionScript Design Patterns
ActionScript Design Patterns ActionScript Design Patterns
ActionScript Design Patterns Yoss Cohen
 
Mocking vtcc3 - en
Mocking   vtcc3 - enMocking   vtcc3 - en
Mocking vtcc3 - envgrondin
 
Dot Net Interview Questions - Part 1
Dot Net Interview Questions - Part 1Dot Net Interview Questions - Part 1
Dot Net Interview Questions - Part 1ReKruiTIn.com
 
Caliburn.micro
Caliburn.microCaliburn.micro
Caliburn.microbwullems
 
Linux Assignment 3
Linux Assignment 3Linux Assignment 3
Linux Assignment 3Diane Allen
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011YoungSu Son
 

Similar a Common ASP.NET Design Patterns - Telerik India DevCon 2013 (20)

Bartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsBartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design Patterns
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Elements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstElements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code First
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
 
System verilog important
System verilog importantSystem verilog important
System verilog important
 
Enterprise Library 2.0
Enterprise Library 2.0Enterprise Library 2.0
Enterprise Library 2.0
 
.NET TECHNOLOGIES
.NET TECHNOLOGIES.NET TECHNOLOGIES
.NET TECHNOLOGIES
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
 
Stateful mock servers to the rescue on REST ecosystems
Stateful mock servers to the rescue on REST ecosystemsStateful mock servers to the rescue on REST ecosystems
Stateful mock servers to the rescue on REST ecosystems
 
Evolution of Patterns
Evolution of PatternsEvolution of Patterns
Evolution of Patterns
 
ActionScript Design Patterns
ActionScript Design Patterns ActionScript Design Patterns
ActionScript Design Patterns
 
Visual Basic –User Interface- V
Visual Basic –User Interface- VVisual Basic –User Interface- V
Visual Basic –User Interface- V
 
Mocking vtcc3 - en
Mocking   vtcc3 - enMocking   vtcc3 - en
Mocking vtcc3 - en
 
Dot Net Interview Questions - Part 1
Dot Net Interview Questions - Part 1Dot Net Interview Questions - Part 1
Dot Net Interview Questions - Part 1
 
Caliburn.micro
Caliburn.microCaliburn.micro
Caliburn.micro
 
Linux Assignment 3
Linux Assignment 3Linux Assignment 3
Linux Assignment 3
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
C sharp
C sharpC sharp
C sharp
 

Más de Steven Smith

Clean architecture with asp.net core by Ardalis
Clean architecture with asp.net core by ArdalisClean architecture with asp.net core by Ardalis
Clean architecture with asp.net core by ArdalisSteven Smith
 
Finding Patterns in the Clouds - Cloud Design Patterns
Finding Patterns in the Clouds - Cloud Design PatternsFinding Patterns in the Clouds - Cloud Design Patterns
Finding Patterns in the Clouds - Cloud Design PatternsSteven Smith
 
Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018Steven Smith
 
Introducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemashIntroducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemashSteven Smith
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing SoftwareSteven Smith
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Steven Smith
 
Decoupling with Domain Events
Decoupling with Domain EventsDecoupling with Domain Events
Decoupling with Domain EventsSteven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Steven Smith
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Steven Smith
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
A Whirldwind Tour of ASP.NET 5
A Whirldwind Tour of ASP.NET 5A Whirldwind Tour of ASP.NET 5
A Whirldwind Tour of ASP.NET 5Steven Smith
 
My Iraq Experience
My Iraq ExperienceMy Iraq Experience
My Iraq ExperienceSteven Smith
 
Add Some DDD to Your ASP.NET MVC, OK?
Add Some DDD to Your ASP.NET MVC, OK?Add Some DDD to Your ASP.NET MVC, OK?
Add Some DDD to Your ASP.NET MVC, OK?Steven Smith
 
Domain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVCDomain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVCSteven Smith
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing SoftwareSteven Smith
 

Más de Steven Smith (20)

Clean architecture with asp.net core by Ardalis
Clean architecture with asp.net core by ArdalisClean architecture with asp.net core by Ardalis
Clean architecture with asp.net core by Ardalis
 
Finding Patterns in the Clouds - Cloud Design Patterns
Finding Patterns in the Clouds - Cloud Design PatternsFinding Patterns in the Clouds - Cloud Design Patterns
Finding Patterns in the Clouds - Cloud Design Patterns
 
Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018
 
Introducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemashIntroducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemash
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
 
Decoupling with Domain Events
Decoupling with Domain EventsDecoupling with Domain Events
Decoupling with Domain Events
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
A Whirldwind Tour of ASP.NET 5
A Whirldwind Tour of ASP.NET 5A Whirldwind Tour of ASP.NET 5
A Whirldwind Tour of ASP.NET 5
 
Domain events
Domain eventsDomain events
Domain events
 
My Iraq Experience
My Iraq ExperienceMy Iraq Experience
My Iraq Experience
 
Add Some DDD to Your ASP.NET MVC, OK?
Add Some DDD to Your ASP.NET MVC, OK?Add Some DDD to Your ASP.NET MVC, OK?
Add Some DDD to Your ASP.NET MVC, OK?
 
Domain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVCDomain-Driven Design with ASP.NET MVC
Domain-Driven Design with ASP.NET MVC
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing Software
 

Último

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Common ASP.NET Design Patterns - Telerik India DevCon 2013

  • 1. Common ASP.NET Design Patterns Steve Smith @ardalis | ardalis.com Telerik http://flic.kr/p/4MEeVn
  • 3. Stages of Learning Stage Zero - Ignorance Stage One - Awakening Stage Two - Overzealous Stage Three – Mastery http://flic.kr/p/6StgW5
  • 5. Actual Usage  Twitter Poll in 2011 w/342 responses  http://twtpoll.com/r/t7jzrx Votes 250 200 150 100 50 Votes 0
  • 6. Common Design Patterns 0.Singleton 1.Strategy 2.Repository 3.Proxy (Of course there are many others!) 4.Command 5.Factory
  • 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”
  • 10. How Singleton Is Used  Call methods on Instance directly  Assign variables to Instance  Pass as Parameter
  • 11. Singleton Structure (thread-safe and fast) Source: http://csharpindepth.com/Articles/General/Singleton.aspx
  • 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. Managing Object Lifetime Using an IOC Container
  • 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
  • 17. Strategy : Common Usage  Dependency Inversion and Dependency Injection  Decouple class dependencies and responsibilities Refactoring 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. 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. “New is Glue” “new” creates tight coupling between classes Be conscious of the consequences of using “new” If you need loose coupling, replace “new” with Strategy Pattern http://flic.kr/p/aN4Zv
  • 21. Data Access Evolution No 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. 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. 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. 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
  • 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 the Strategy Pattern. Use the local field of this interface type in place of previous implementation code.
  • 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. Proxy
  • 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
  • 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. Proxy – CachedRepository Implementation
  • 33. Implementing with IOC // Strategy Pattern with Proxy Pattern (using composition) x.For<IAlbumRepository>().Use<CachedAlbumRepository>() .Ctor<IAlbumRepository>().Is<EfAlbumRepository>();
  • 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
  • 37. Command : Usage  Great for representing state transitions (the arrows below) Pending Archived Published
  • 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. Practice PDD  Pain  Driven  Development If it’s causing pain, fix it.
  • 41. Design Patterns in Action CODE WALKTHROUGH
  • 42. A Tale from the REAL WORLD
  • 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/aA4RS6 Pluralsight 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. 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

Notas del editor

  1. General, reusable solutions to common problemsNot a complete, finished solutionA template, recipe, or approach to solving certain problemsEach has a specific name, so we can discuss common elements of design using a common vocabulary
  2. Learning anything – a musical chord, a martial arts technique, etc.Zero: You used a what? Never heard of it.Awakening:Wow, I just learned how XYZ pattern can improve my design. I’m not really sure where it would work in my code, but I’m definitely looking.Overzealous:I totally “get” the XYZ pattern; I’m adding it everywhere I can shoehorn it into my code. My design’s gonna be better now, for sure!Mastery: In response to some specific design pain points, the XYZ pattern was a logical next step and was achieved through a simple refactoring.
  3. Design pattern names provide placeholders or complex abstractions and sets of refactorings. Consider the difference between:We have some tight coupling to the database here. We can probably fix it if we apply these refactorings;extract an interface, extract a method, Extract a class,Replace local with parameterORLet’s apply the Repository pattern to fix it.
  4. Used Regularly or Daily by most respondentsFactory (194)Repository (185)Iterator (139)Adapter/Wrapper (122)Observer (113)Command (106)Singleton (105)Strategy (101)Proxy (91)
  5. It’s possible for the new Singleton(); line to be called more than once.
  6. Here are three example registration commands using an IOC container, in this case StructureMap. If you’re not familiar with IOC containers, they’re basically just factories on steroids, which you configure to create instances of types according to certain rules.In the first case, one new instance of the type is created per thread, or per HTTP request. Thus, in an ASP.NET application, a new DbContext will be created with each new web request, but if we used this same code in a non-web context, such as in an integration test, it would create a single instance per thread. In the second case, the Singleton() call will literally configure the lifetime of the instance to be a singleton, with one and only one instance available for the life of this application. In the last, default case, each new request for an instance will get its own, separate instance of the requested type.The benefit of this approach is that it makes it very clear which objects are configured with which lifetimes, and none of the objects themselves are cluttered with these concerns. The resulting code has less repetition, is simpler, and its classes have fewer responsibilities.
  7. Note – this cannot easily be tested without an actual database instance in place.
  8. http://en.wikipedia.org/wiki/File:Proxy_concept_en.svg
  9. Apply patterns via refactoring,Not Big Design Up Front
  10. Show the MvcMusicStore applicationHg clone https://hg.codeplex.com/forks/ssmith/mvcmusicstorerepositorypattern 
  11. Talk about the CacheDependencyBug in AdSignia and how it was introduced by moving a hard-coded instantiation to a parameter, and then fixed by replacing the parameter with a Factory (lambda).