SlideShare ist ein Scribd-Unternehmen logo
1 von 77
Design Patterns
Steve Smith (@ardalis)
steve@ardalis.com
Ardalis.com
Podcast: WeeklyDevTips.com
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
Design Patterns
Composite
Iterator
Specification
Unit of
Work
Most Useful (for web app design)
(Singleton)
Strategy
Repository
Proxy
Command
Factory
Null Object
(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 is not thread-safe
 Avoid in multi-threaded environments
 Avoid in web server scenarios (e.g. ASP.NET)
 Introduce tight coupling among collaborating
classes
 Singletons are notoriously difficult to test
 Commonly regarded as an anti-pattern
Some commercial tools
can be used to mock and
test Singletons
But why would you
intentionally write code
you can only test with
certain premium tools?
Singleton Consequences
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 (StructureMap)
Object Lifetime in ASP.NET Core
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// you don’t need to implement singleton behavior in class!
services.AddSingleton<ISomeService>();
}
Singleton behavior is fine and
often desirable.
Implementing this behavior using the
Singleton Pattern on the class itself is
usually not ideal.
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 in my Pluralsight course:
 http://bit.ly/SOLID-OOP
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
Follow the Explicit Dependencies Principle
 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”
Be conscious of the
consequences of using
“new”
If you need loose coupling,
replace “new” with Strategy
Pattern
http://flic.kr/p/aN4Zv
“new” creates tight coupling
between classes
Also works with WebForms
Repository
Data Access Evolution
Initially no separation of concerns
 Data access logic baked directly into UI
ASP.NET Data Source Controls
Classic ASP scripts
 Data access logic in UI layer via codebehind
ASP.NET Page_Load event
ASP.NET Button_Click event
User Interface
Database
Compile Time
Runtime
Data Access : Helper
Classes
 Calls to data made through a
utility
 Example: Data Access
Application Block (SqlHelper)
 Logic may still live in UI layer
 Or a Business Logic Layer may
make calls to a Data Access
Layer which might then call the
helper
User Interface
Database
Compile Time
Runtime
Helper Class
What’s Missing?
Abstraction!
 No way to abstract away data
access
 Tight coupling
 Leads to Big Ball of Mud
system
 Solution:
Depend on interfaces, not
concrete implementations
What should we call such
interfaces? Repositories!
User Interface
Database
Compile Time
Runtime
Core
IFooRepository
Infrastructure
SqlFooRepository
Repository
 A Data Access Pattern
Introduced as part of Domain-Driven Design, but very popular outside of DDD as well
 Separates persistence responsibility from business classes
 Enables
Single Responsibility Principle
Separation of Concerns
Testability
Repository
 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 (a Domain-Driven Design concept)
Consider!
 Repositories should return domain objects
Don’t let persistence concerns leak through the repository interface
 What should Repository List methods return?
IEnumerable<T>
IQueryable<T>
 What about deferred execution?
 What about lazy loading?
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 (app entry point) references Core
Accesses Infrastructure at runtime
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
Bonus Pattern: Decorator!
Stacking Patterns
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 (StructureMap)
// Strategy Pattern with Proxy Pattern (using composition)
x.For<IAlbumRepository>().Use<CachedAlbumRepository>()
.Ctor<IAlbumRepository>().Is<EfAlbumRepository>();
// Doesn’t work:
x.For<IAlbumRepository>().Use<CachedAlbumRepository>();
Implementing with IOC (.NET Core)
services.AddTransient<IDataService, DataService>((ctx) =>
{
IOtherService svc = ctx.GetService<IOtherService>();
return new DataService(svc);
});
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
 A Command is a message
 Common scenarios:
Delayed execution
Logging activity
Enabling Undo / Revoke Transaction functionality
Command : Usage
 Combine with messaging for scalability
 What happens when you complete an order from Amazon?
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
Lazy<T>
 Provide simple built-in Factory behavior for lazy loading
 Available in .NET Framework 4, 4.5, later
 Learn more:
 http://msdn.microsoft.com/en-us/magazine/ff898407.aspx
Without Lazy<T>
With Lazy<T>
Alternate Factories
Write your own method
Use an IOC Container
Lambda expressions
 Func<ExpensiveObject> factory
 () => new ExpensiveObject();
“IOC Containers are
basically just factories on
steroids.”
Null Object
Nulls
Nulls
“I call it my billion-dollar mistake. It
was the invention of the null
reference in 1965.”
Sir Charles Antony Richard Hoare
Null Object
Replace null with an actual instance object with
default values
Reduce number of null checks in application
Allow methods on this “null” object to be called,
without generating reference exceptions
Use When…
A method requires a collaborator
 And you want to ensure it is never null
It’s necessary to support a “do nothing” option
 Especially with Command or Strategy
Implementation
BaseType
Real Objects
The Null object is simply another implementation of a base
type (class or interface)
For ease of use, it is often added as a static property on BaseType (e.g.
BaseType.Null or BaseType.NotSet)
NullObject
Nulls Break Polymorphism
 Polymorphism is a key benefit of OO systems
 Null breaks polymorphism – calling methods on null instances results in
exceptions
Null Checks Everywhere
With Null Object
Repository:
Client code:
Practice PDD
 Pain Driven Development
If it’s causing pain, fix it.
“Don’t apply every pattern
you know to a problem
from the start; practice
Pain Driven Development.”
Let’s Review
Real World Design Patterns
1. Don’t be too busy to improve
2. Avoid adding coupling via Singletons
3. Decouple specific implementation with
Strategy
4. Avoid hidden dependencies – New is Glue!
5. Decouple your database with Repository
6. Decouple access control with Proxy
7. Decouple execution of other actions with Commands
8. Decouple construction with Factory
9. Reduce null checks with Null Object
10. Practice Pain Driven Development
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
Discuss
Contact
steve@ardalis.com
Twitter: @ardalis
Web: ardalis.com
http://about.me/stevenasmith

Weitere ähnliche Inhalte

Was ist angesagt?

Api gateway
Api gatewayApi gateway
Api gatewayenyert
 
Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...
Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...
Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...Edureka!
 
PLAT-13 Metadata Extraction and Transformation
PLAT-13 Metadata Extraction and TransformationPLAT-13 Metadata Extraction and Transformation
PLAT-13 Metadata Extraction and TransformationAlfresco Software
 
Git the fast version control system
Git the fast version control systemGit the fast version control system
Git the fast version control systemJeroen Rosenberg
 
Intro to git and git hub
Intro to git and git hubIntro to git and git hub
Intro to git and git hubVenkat Malladi
 
REST API Best (Recommended) Practices
REST API Best (Recommended) PracticesREST API Best (Recommended) Practices
REST API Best (Recommended) PracticesRasheed Waraich
 
Microservice Architecture
Microservice ArchitectureMicroservice Architecture
Microservice ArchitectureNguyen Tung
 
Three layer API Design Architecture
Three layer API Design ArchitectureThree layer API Design Architecture
Three layer API Design ArchitectureHarish Kumar
 
Architecting an Enterprise API Management Strategy
Architecting an Enterprise API Management StrategyArchitecting an Enterprise API Management Strategy
Architecting an Enterprise API Management StrategyWSO2
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHubJames Gray
 
Discovering the 2 in Alfresco Search Services 2.0
Discovering the 2 in Alfresco Search Services 2.0Discovering the 2 in Alfresco Search Services 2.0
Discovering the 2 in Alfresco Search Services 2.0Angel Borroy López
 
How Netflix Monitors Applications in Near Real-time w Amazon Kinesis - ABD401...
How Netflix Monitors Applications in Near Real-time w Amazon Kinesis - ABD401...How Netflix Monitors Applications in Near Real-time w Amazon Kinesis - ABD401...
How Netflix Monitors Applications in Near Real-time w Amazon Kinesis - ABD401...Amazon Web Services
 
Log analysis with the elk stack
Log analysis with the elk stackLog analysis with the elk stack
Log analysis with the elk stackVikrant Chauhan
 
Metadata Extraction and Content Transformation
Metadata Extraction and Content TransformationMetadata Extraction and Content Transformation
Metadata Extraction and Content TransformationAlfresco Software
 
Creative Branching Models for Multiple Release Streams
Creative Branching Models for Multiple Release StreamsCreative Branching Models for Multiple Release Streams
Creative Branching Models for Multiple Release StreamsAtlassian
 
Effective API Governance: Lessons Learnt
Effective API Governance: Lessons LearntEffective API Governance: Lessons Learnt
Effective API Governance: Lessons LearntPronovix
 

Was ist angesagt? (20)

Api gateway
Api gatewayApi gateway
Api gateway
 
Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...
Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...
Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...
 
PLAT-13 Metadata Extraction and Transformation
PLAT-13 Metadata Extraction and TransformationPLAT-13 Metadata Extraction and Transformation
PLAT-13 Metadata Extraction and Transformation
 
Git the fast version control system
Git the fast version control systemGit the fast version control system
Git the fast version control system
 
Intro to git and git hub
Intro to git and git hubIntro to git and git hub
Intro to git and git hub
 
Apache Solr Workshop
Apache Solr WorkshopApache Solr Workshop
Apache Solr Workshop
 
Git and github 101
Git and github 101Git and github 101
Git and github 101
 
REST API Best (Recommended) Practices
REST API Best (Recommended) PracticesREST API Best (Recommended) Practices
REST API Best (Recommended) Practices
 
Microservice Architecture
Microservice ArchitectureMicroservice Architecture
Microservice Architecture
 
Three layer API Design Architecture
Three layer API Design ArchitectureThree layer API Design Architecture
Three layer API Design Architecture
 
Architecting an Enterprise API Management Strategy
Architecting an Enterprise API Management StrategyArchitecting an Enterprise API Management Strategy
Architecting an Enterprise API Management Strategy
 
API Governance
API Governance API Governance
API Governance
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHub
 
Discovering the 2 in Alfresco Search Services 2.0
Discovering the 2 in Alfresco Search Services 2.0Discovering the 2 in Alfresco Search Services 2.0
Discovering the 2 in Alfresco Search Services 2.0
 
Storage and Alfresco
Storage and AlfrescoStorage and Alfresco
Storage and Alfresco
 
How Netflix Monitors Applications in Near Real-time w Amazon Kinesis - ABD401...
How Netflix Monitors Applications in Near Real-time w Amazon Kinesis - ABD401...How Netflix Monitors Applications in Near Real-time w Amazon Kinesis - ABD401...
How Netflix Monitors Applications in Near Real-time w Amazon Kinesis - ABD401...
 
Log analysis with the elk stack
Log analysis with the elk stackLog analysis with the elk stack
Log analysis with the elk stack
 
Metadata Extraction and Content Transformation
Metadata Extraction and Content TransformationMetadata Extraction and Content Transformation
Metadata Extraction and Content Transformation
 
Creative Branching Models for Multiple Release Streams
Creative Branching Models for Multiple Release StreamsCreative Branching Models for Multiple Release Streams
Creative Branching Models for Multiple Release Streams
 
Effective API Governance: Lessons Learnt
Effective API Governance: Lessons LearntEffective API Governance: Lessons Learnt
Effective API Governance: Lessons Learnt
 

Ähnlich wie Most Useful Design Patterns

Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Steven Smith
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Steven Smith
 
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
 
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
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patternsamitarcade
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Pythondn
 
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
 
Writting Better Software
Writting Better SoftwareWritting Better Software
Writting Better Softwaresvilen.ivanov
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern11prasoon
 
Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013Steven Smith
 
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
 

Ähnlich wie Most Useful Design Patterns (20)

Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013Common ASP.NET Design Patterns - Telerik India DevCon 2013
Common ASP.NET Design Patterns - Telerik India DevCon 2013
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
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
 
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
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
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
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Design pattern
Design patternDesign pattern
Design pattern
 
Writting Better Software
Writting Better SoftwareWritting Better Software
Writting Better Software
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
 
Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013
 
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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 

Kürzlich hochgeladen (20)

GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 

Most Useful Design Patterns

  • 1. Design Patterns Steve Smith (@ardalis) steve@ardalis.com Ardalis.com Podcast: WeeklyDevTips.com
  • 2.
  • 3.
  • 5. Stages of Learning Stage Zero - Ignorance Stage One - Awakening Stage Two - Overzealous Stage Three – Mastery http://flic.kr/p/6StgW5
  • 8. Most Useful (for web app design) (Singleton) Strategy Repository Proxy Command Factory Null Object
  • 10. 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”
  • 11. Singleton Structure (not thread-safe)
  • 12. How Singleton Is Used  Call methods on Instance directly  Assign variables to Instance  Pass as Parameter
  • 13. Singleton Structure (thread-safe and fast) Source: http://csharpindepth.com/Articles/General/Singleton.aspx
  • 14. Singleton Consequences  The default implementation is not thread-safe  Avoid in multi-threaded environments  Avoid in web server scenarios (e.g. ASP.NET)  Introduce tight coupling among collaborating classes  Singletons are notoriously difficult to test  Commonly regarded as an anti-pattern Some commercial tools can be used to mock and test Singletons But why would you intentionally write code you can only test with certain premium tools?
  • 15. Singleton Consequences 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
  • 16. Managing Object Lifetime Using an IOC Container (StructureMap)
  • 17. Object Lifetime in ASP.NET Core public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // you don’t need to implement singleton behavior in class! services.AddSingleton<ISomeService>(); }
  • 18. Singleton behavior is fine and often desirable. Implementing this behavior using the Singleton Pattern on the class itself is usually not ideal.
  • 20. 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 in my Pluralsight course:  http://bit.ly/SOLID-OOP
  • 22. 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
  • 23. Hidden Dependencies  Classes should declare their dependencies via their constructor Follow the Explicit Dependencies Principle  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
  • 24. “New is Glue” Be conscious of the consequences of using “new” If you need loose coupling, replace “new” with Strategy Pattern http://flic.kr/p/aN4Zv “new” creates tight coupling between classes
  • 25. Also works with WebForms
  • 26.
  • 28. Data Access Evolution Initially no separation of concerns  Data access logic baked directly into UI ASP.NET Data Source Controls Classic ASP scripts  Data access logic in UI layer via codebehind ASP.NET Page_Load event ASP.NET Button_Click event User Interface Database Compile Time Runtime
  • 29. Data Access : Helper Classes  Calls to data made through a utility  Example: Data Access Application Block (SqlHelper)  Logic may still live in UI layer  Or a Business Logic Layer may make calls to a Data Access Layer which might then call the helper User Interface Database Compile Time Runtime Helper Class
  • 30. What’s Missing? Abstraction!  No way to abstract away data access  Tight coupling  Leads to Big Ball of Mud system  Solution: Depend on interfaces, not concrete implementations What should we call such interfaces? Repositories! User Interface Database Compile Time Runtime Core IFooRepository Infrastructure SqlFooRepository
  • 31. Repository  A Data Access Pattern Introduced as part of Domain-Driven Design, but very popular outside of DDD as well  Separates persistence responsibility from business classes  Enables Single Responsibility Principle Separation of Concerns Testability
  • 32. Repository  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 (a Domain-Driven Design concept)
  • 33. Consider!  Repositories should return domain objects Don’t let persistence concerns leak through the repository interface  What should Repository List methods return? IEnumerable<T> IQueryable<T>  What about deferred execution?  What about lazy loading?
  • 35. 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.
  • 36. 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 (app entry point) references Core Accesses Infrastructure at runtime Responsible for creating object graph, either manually or via an IOC Container
  • 37. Proxy
  • 38. 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
  • 42. 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
  • 43. Proxy – CachedRepository Implementation
  • 44. Implementing with IOC (StructureMap) // Strategy Pattern with Proxy Pattern (using composition) x.For<IAlbumRepository>().Use<CachedAlbumRepository>() .Ctor<IAlbumRepository>().Is<EfAlbumRepository>(); // Doesn’t work: x.For<IAlbumRepository>().Use<CachedAlbumRepository>();
  • 45. Implementing with IOC (.NET Core) services.AddTransient<IDataService, DataService>((ctx) => { IOtherService svc = ctx.GetService<IOtherService>(); return new DataService(svc); });
  • 47. Command  Represent an action as an object  Decouple performing the action from the client that is issuing the command  A Command is a message  Common scenarios: Delayed execution Logging activity Enabling Undo / Revoke Transaction functionality
  • 48. Command : Usage  Combine with messaging for scalability  What happens when you complete an order from Amazon?
  • 50. 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
  • 51. Lazy<T>  Provide simple built-in Factory behavior for lazy loading  Available in .NET Framework 4, 4.5, later  Learn more:  http://msdn.microsoft.com/en-us/magazine/ff898407.aspx
  • 54. Alternate Factories Write your own method Use an IOC Container Lambda expressions  Func<ExpensiveObject> factory  () => new ExpensiveObject(); “IOC Containers are basically just factories on steroids.”
  • 56. Nulls
  • 57. Nulls “I call it my billion-dollar mistake. It was the invention of the null reference in 1965.” Sir Charles Antony Richard Hoare
  • 58. Null Object Replace null with an actual instance object with default values Reduce number of null checks in application Allow methods on this “null” object to be called, without generating reference exceptions
  • 59. Use When… A method requires a collaborator  And you want to ensure it is never null It’s necessary to support a “do nothing” option  Especially with Command or Strategy
  • 60. Implementation BaseType Real Objects The Null object is simply another implementation of a base type (class or interface) For ease of use, it is often added as a static property on BaseType (e.g. BaseType.Null or BaseType.NotSet) NullObject
  • 61. Nulls Break Polymorphism  Polymorphism is a key benefit of OO systems  Null breaks polymorphism – calling methods on null instances results in exceptions
  • 64. Practice PDD  Pain Driven Development If it’s causing pain, fix it. “Don’t apply every pattern you know to a problem from the start; practice Pain Driven Development.”
  • 65. Let’s Review Real World Design Patterns
  • 66. 1. Don’t be too busy to improve
  • 67. 2. Avoid adding coupling via Singletons
  • 68. 3. Decouple specific implementation with Strategy
  • 69. 4. Avoid hidden dependencies – New is Glue!
  • 70. 5. Decouple your database with Repository
  • 71. 6. Decouple access control with Proxy
  • 72. 7. Decouple execution of other actions with Commands
  • 73. 8. Decouple construction with Factory
  • 74. 9. Reduce null checks with Null Object
  • 75. 10. Practice Pain Driven Development
  • 76. 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

Hinweis der Redaktion

  1. This is where a lot of people work. Don’t be these guys. When you have a lot of wood to cut, it pays off to periodically sharpen the saw. Sharpening the saw is one of the seven habits of highly effective people. Take time to improve your skills, and practice, and in the long run you will be more effective.
  2. Contact me if you’d like a 30-day pass to Pluralsight. Please consider some of my courses on design patterns, architecture, and domain-driven design.
  3. General, reusable solutions to common problems Not a complete, finished solution A template, recipe, or approach to solving certain problems Each has a specific name, so we can discuss common elements of design using a common vocabulary
  4. 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.
  5. 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 parameter OR Let’s apply the Repository pattern to fix it.
  6. Used Regularly or Daily by most respondents Factory (194) Repository (185) Iterator (139) Adapter/Wrapper (122) Observer (113) Command (106) Singleton (105) Strategy (101) Proxy (91)
  7. This joke is probably dating me – how many of you know the Highlander these days?
  8. It’s possible for the new Singleton(); line to be called more than once.
  9. Jon Skeet lays out several different ways to implement the Singleton pattern in C#, with different performance and thread safety considerations.
  10. 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.
  11. Add Kragle slide next
  12. If you’re working with web forms, whether adding new features or maintaining a large codebase in which better dependency management would help, realize that you can use dependency injection and the strategy pattern there, too. Doing so with Structuremap typically follows three steps. Create a basepage class and call ObjectFactory.BuildUp(this) in its constructor. This will populate any properties Structuremap knows about in the object. Configure StructureMap to know about certain types by telling it to set all properties of that type. In this case, we’re telling Structuremap to populate any property it finds of type IAlbumRepository In your actual page, add a property of the interface type you want injected. You can now count on this property being supplied by Structuremap.
  13. Remember, although your current strategy may be beautiful, you need to occasionally check to see how well it’s actually working. Using the strategy pattern, if you find that a particular implementation isn’t working, you can easily swap it out for another one.
  14. In my own career as a developer, I’ve seen an evolution in how most data access is performed. I started with classic ASP and soon after, the first version of ASP.NET. In both cases, there was typically little separation of concerns between UI, business rules, and data access. This tended to result in a lot of duplicate concepts and code, as well as direct dependence on a database.
  15. To address the duplication, helper classes were often created to take repetitive tasks and centralize them. However, in this case the runtime program flow still mirrored the compile time dependency tree, in both cases targeting a database. This made testing such applications difficult.
  16. The problem with these approaches is that there is no abstraction layer between the application and its infrastructure – in this case the database.
  17. Consider grabbing repository image from DDD slide here Split into two slides
  18. Note – this cannot easily be tested without an actual database instance in place.
  19. Add image showing Onion Architecture and/or a simple solution with Core, Infrastructure, and Web.
  20. http://en.wikipedia.org/wiki/File:Proxy_concept_en.svg
  21. Note that the structure of the Proxy is very similar to the Strategy pattern, which we already saw (click). The key difference between the two is in the intent. Note that this is just one Proxy implementation – it can also be achieved with a proxy class that inherits from the subject class, rather than sharing a common interface implementation.
  22. TODO: Show an example of adding caching logic to a repository without any separation of concerns. Consider starting with an MVC method that does direct data access without any repository, uses caching, etc, and lament its lack of testability. Perhaps a Music Store method, maybe with some modification.
  23. Maybe look for an image representing military orders being received
  24. Ask about Amazon and what actually happens when you place an order there, compared to with most other online stores.
  25. The background for this slide is the FirstOrDefault image I liked for the Null Object pattern
  26. Some polymorphic code
  27. Change this to something that isn’t displayed in the UI layer, such as a function that must be called or a number to be summed.
  28. Apply patterns via refactoring, Not Big Design Up Front
  29. Show the MvcMusicStore application Hg clone https://hg.codeplex.com/forks/ssmith/mvcmusicstorerepositorypattern 
  30. 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).
  31. Update with imagery and review of patterns and when to use them. Fewer words. Don’t be too busy to improve Avoid adding coupling to your system with Singleton Decouple specific implementation from use with Strategy Avoid hidden dependencies; remember New is Glue! Decouple your database with Repository Decouple caching, lazy loading, and other access concerns with Proxy Decouple execution of other actions with Commands Decouple construction with Factory – remember Lazy<T> and lambda as factory shortcuts Cut down on prolific null checks with the Null Object Pattern Don’t try to use every pattern up front – practice Pain Driven Development
  32. Update with imagery and review of patterns and when to use them. Fewer words. Don’t be too busy to improve Avoid adding coupling to your system with Singleton Decouple specific implementation from use with Strategy Avoid hidden dependencies; remember New is Glue! Decouple your database with Repository Decouple caching, lazy loading, and other access concerns with Proxy Decouple execution of other actions with Commands Decouple construction with Factory – remember Lazy<T> and lambda as factory shortcuts Cut down on prolific null checks with the Null Object Pattern Don’t try to use every pattern up front – practice Pain Driven Development
  33. Update with imagery and review of patterns and when to use them. Fewer words. Don’t be too busy to improve Avoid adding coupling to your system with Singleton Decouple specific implementation from use with Strategy Avoid hidden dependencies; remember New is Glue! Decouple your database with Repository Decouple caching, lazy loading, and other access concerns with Proxy Decouple execution of other actions with Commands Decouple construction with Factory – remember Lazy<T> and lambda as factory shortcuts Cut down on prolific null checks with the Null Object Pattern Don’t try to use every pattern up front – practice Pain Driven Development
  34. Update with imagery and review of patterns and when to use them. Fewer words. Don’t be too busy to improve Avoid adding coupling to your system with Singleton Decouple specific implementation from use with Strategy Avoid hidden dependencies; remember New is Glue! Decouple your database with Repository Decouple caching, lazy loading, and other access concerns with Proxy Decouple execution of other actions with Commands Decouple construction with Factory – remember Lazy<T> and lambda as factory shortcuts Cut down on prolific null checks with the Null Object Pattern Don’t try to use every pattern up front – practice Pain Driven Development
  35. Update with imagery and review of patterns and when to use them. Fewer words. Don’t be too busy to improve Avoid adding coupling to your system with Singleton Decouple specific implementation from use with Strategy Avoid hidden dependencies; remember New is Glue! Decouple your database with Repository Decouple caching, lazy loading, and other access concerns with Proxy Decouple execution of other actions with Commands Decouple construction with Factory – remember Lazy<T> and lambda as factory shortcuts Cut down on prolific null checks with the Null Object Pattern Don’t try to use every pattern up front – practice Pain Driven Development
  36. Update with imagery and review of patterns and when to use them. Fewer words. Don’t be too busy to improve Avoid adding coupling to your system with Singleton Decouple specific implementation from use with Strategy Avoid hidden dependencies; remember New is Glue! Decouple your database with Repository Decouple caching, lazy loading, and other access concerns with Proxy Decouple execution of other actions with Commands Decouple construction with Factory – remember Lazy<T> and lambda as factory shortcuts Cut down on prolific null checks with the Null Object Pattern Don’t try to use every pattern up front – practice Pain Driven Development
  37. Update with imagery and review of patterns and when to use them. Fewer words. Don’t be too busy to improve Avoid adding coupling to your system with Singleton Decouple specific implementation from use with Strategy Avoid hidden dependencies; remember New is Glue! Decouple your database with Repository Decouple caching, lazy loading, and other access concerns with Proxy Decouple execution of other actions with Commands Decouple construction with Factory – remember Lazy<T> and lambda as factory shortcuts Cut down on prolific null checks with the Null Object Pattern Don’t try to use every pattern up front – practice Pain Driven Development
  38. Decouple construction with Factory Remember Lazy<T> and lambda as factory shortcuts Remember IOC containers are factories on steroids
  39. Decouple construction with Factory Remember Lazy<T> and lambda as factory shortcuts Remember IOC containers are factories on steroids
  40. Don’t try to apply every pattern you know up front.
  41. Update PS links to use referral links