SlideShare a Scribd company logo
Refactoring Applications
      using SOLID Principles

                       Steve Smith
                           Telerik
                   ardalis.com @ardalis



www.devreach.com

   
   
   




www.devreach.com
Preventive Maintenance
   • Refactoring
        – Eliminate Duplication
        – Simplify Design


   • Automated Tests
        – Verify correctness
        – Avoid regressions
        – Increase Confidence

www.devreach.com
Refactoring Process
   • Verify existing behavior
   • Write Characterization Tests if none exist
        – Find test points
        – Break dependencies
   • Apply Refactoring
   • Confirm existing behavior is preserved



www.devreach.com
Characterization Tests
   Process
   1. Write a test you know will fail
   2. Use the output of the failing test to
      determine the existing behavior to assert
   3. Update the test with the new
      value/behavior
   4. Run the test again – it should pass


www.devreach.com
SOLID
  Principles



               http://flickr.com/photos/kevinkemmerer/2772526725
Principles of OO Design
   0. Don’t Repeat Yourself (DRY)

   1. Single Responsibility
   2. Open/Closed
   3. Liskov Substitution
   4. Interface Segregation
   5. Dependency Inversion

www.devreach.com
Don’t Repeat
   Repeat Yourself
   • Duplication in logic calls for abstraction

   • Duplication in process calls for
     automation




www.devreach.com
Common Refactorings
   •   Replace Magic Number/String
   •   Parameterize Method
   •   Pull Up Field
   •   Pull Up Method
   •   Replace Conditional With Polymorphism
   •   Introduce Method



www.devreach.com
Role Checks
    if(user.IsInRole(“Admins”)
    {
      // allow access to resource
    }

    // favor privileges over role checks
    // ardalis.com/Favor-Privileges-over-Role-Checks

    var priv = new ContentPrivilege(user, article);
    if(priv.CanEdit())
    {
      // allow access
    }

www.devreach.com
Single Responsibility Principle
   The Single Responsibility Principle states that every object
     should have a single responsibility, and that
     responsibility should be entirely encapsulated by the
     class.
                                                      Wikipedia

   There should never be more than one reason for a class to
     change.
                                Robert C. “Uncle Bob” Martin




www.devreach.com
Example Responsibilities
   •   Persistence
   •   Validation
   •   Notification
   •   Error Handling
   •   Logging
   •   Class Selection / Construction
   •   Formatting
   •   Parsing
   •   Mapping


www.devreach.com
Dependency and Coupling
   • Excessive coupling makes changing
     legacy software difficult

   • Breaking apart responsibilities and
     dependencies is a large part of working
     with existing code




www.devreach.com
Common Refactorings
   • Extract Class
   • Move Method




www.devreach.com
Heuristics and Code Smells
   • Visual Studio Metrics




www.devreach.com
Code Smell: Regions




   More on Regions: http://ardalis.com/regional-differences
www.devreach.com
Open / Closed Principle
   The Open / Closed Principle states that software entities
     (classes, modules, functions, etc.) should be open for
     extension, but closed for modification.
                                                     Wikipedia




www.devreach.com
Open / Closed Principle
   Open to Extension
     New behavior can be added in the future

   Closed to Modification
     Changes to source or binary code are not required




   Dr. Bertrand Meyer originated the OCP term in his 1988
     book, Object Oriented Software Construction


www.devreach.com
Common Refactorings
   • Extract Interface / Apply Strategy Pattern
   • Parameterize Method
   • Form Template Method




www.devreach.com
OCP Fail




www.devreach.com
OCP Fail
    public bool IsSpecialCustomer(Customer c)
    {
      if(c.Country == “US” && c.Balance < 50)   return   false;
      if(c.Country == “DE” && c.Balance < 25)   return   false;
      if(c.Country == “UK” && c.Balance < 35)   return   false;
      if(c.Country == “FR” && c.Balance < 27)   return   false;
      if(c.Country == “BG” && c.Balance < 29)   return   false;

        if(c.Age < 18 || c.Age > 65) return false;

        if(c.Income < 50000 && c.Age < 30) return false;
        return true;
    }

www.devreach.com
OCP OK
    private IEnumerable<ICustomerRule> _rules;

    public bool IsSpecialCustomer(Customer c)
    {
      foreach(var rule in _rules)
      {
        if(rule.Evaluate(c) == false) return false;
      }
      return true;
    }




www.devreach.com
Liskov Substitution Principle
   The Liskov Substitution Principle states that
    Subtypes must be substitutable for their
    base types.
     Agile Principles, Patterns, and Practices in
                                              C#

   Named for Barbara Liskov, who first
    described the principle in 1988.

www.devreach.com
Common Refactorings
   • Collapse Hierarchy
   • Pull Up / Push Down Field
   • Pull Up / Push Down Method




www.devreach.com
Liskov Substitution Fail
    foreach(var employee in employees)
    {
      if(employee is Manager)
      {
        Helpers.PrintManager(employee as Manager);
        break;
      }
      Helpers.PrintEmployee(employee);
    }



www.devreach.com
Liskov Substitution OK
    foreach(var employee in employees)
    {
      employee.Print();
      // or
      Helpers.PrintEmployee(employee);
    }




www.devreach.com
Interface Segregation Principle
   The Interface Segregation Principle states that
     Clients should not be forced to depend on
     methods they do not use.
        Agile Principles, Patterns, and Practices in C#

   Corollary:
        Prefer small, cohesive interfaces to “fat” interfaces




www.devreach.com
Common Refactorings
   • Extract Interface




www.devreach.com
ISP Fail (sometimes)
    public IRepository<T>
    {
      T GetById(int id);
      IEnumerable<T> List();
      void Create(T item);
      void Update(T item);
      void Delete(T item);
    }




www.devreach.com
ISP OK (for CQRS for example)
    public IRepository<T> : IReadRepository<T>,
                             IWriteRepository<T>
    { }
    public IReadRepository<T>
    {
      T GetById(int id);
      IEnumerable<T> List();
    }
    public IWriteRepository<T>
      void Create(T item);
      void Update(T item);
      void Delete(T item);
    }

www.devreach.com
Dependency Inversion Principle
   High-level modules should not depend on low-level
     modules. Both should depend on abstractions.

   Abstractions should not depend on details. Details
     should depend on abstractions.
        Agile Principles, Patterns, and Practices in C#




www.devreach.com
Dependency Inversion Principle
   • Depend on Abstractions
        – Interfaces, not concrete types


   • Inject Dependencies into Classes

   • Structure Solution so Dependencies Flow
     Toward Core
        – Onion Architecture

www.devreach.com
Application Layers




www.devreach.com
Compile Time

                     Runtime


                   User Interface
   
        
        


   
        
        
                     Database




www.devreach.com
Compile Time

                       Runtime
   

                   User Interface
   



   
                    Helper Class

   



                     Database




www.devreach.com
Compile Time

                                           Runtime
   
                              User Interface

   

                      Core              Infrastructure
                   IFooRepository      SqlFooRepository
   
        

        
                                Database




www.devreach.com
DIP “Onion” Architecture




www.devreach.com
Common Dependencies
   •   Framework                  See also responsibilities:
   •   Third Party Libraries      • Persistence
                                  • Validation
   •   Database                   • Notification
   •   File System                • Error Handling
   •   Email                      • Logging
   •   Web Services               • Class Selection /
                                     Construction
   •   System Resources (Clock)   • Formatting
   •   Configuration              • Parsing
   •   The new Keyword            • Mapping
   •   Static methods
   •   Thread.Sleep
   •   Random



www.devreach.com
Common Refactorings
   •   Extract Class
   •   Extract Interface / Apply Strategy Pattern
   •   Extract Method
   •   Introduce Service Locator / Container




www.devreach.com
DIP Fail




www.devreach.com
Some Improvement (Façade)




www.devreach.com
DIP OK (Strategy)




www.devreach.com
DIP OK (Strategy)




www.devreach.com
Summary
   • Maintain / Improve Application Code
   • Follow DRY/SOLID Principles
   • Use Characterization Tests to “fix”
     behavior
   • Apply Common Refactorings
   • Re-run Tests After Refactorings



www.devreach.com

        


   
        


   
        


   
        


www.devreach.com
Thank You! – Благодаря!

   Find Me Online:
   Blog: http://ardalis.com
   Twitter: @ardalis
   http://facebook.com/StevenAndrewSmith




www.devreach.com
www.devreach.com

More Related Content

What's hot

Edureka-DevOps-Ebook.pdf
Edureka-DevOps-Ebook.pdfEdureka-DevOps-Ebook.pdf
Edureka-DevOps-Ebook.pdf
relekarsushant
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
Simplilearn
 
Virtual Container - Docker
Virtual Container - Docker Virtual Container - Docker
Virtual Container - Docker
Venkata Naga Ravi
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
NexThoughts Technologies
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Hùng Nguyễn Huy
 
Universal React apps in Next.js
Universal React apps in Next.jsUniversal React apps in Next.js
Universal React apps in Next.js
🐕 Łukasz Ostrowski
 
Build Automation using Maven
Build Automation using Maven Build Automation using Maven
Build Automation using Maven
Ankit Gubrani
 
Clean architecture with asp.net core
Clean architecture with asp.net coreClean architecture with asp.net core
Clean architecture with asp.net core
Sam Nasr, MCSA, MVP
 
Inside GitHub with Chris Wanstrath
Inside GitHub with Chris WanstrathInside GitHub with Chris Wanstrath
Inside GitHub with Chris Wanstrath
SV Ruby on Rails Meetup
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | Edureka
Edureka!
 
Lessons Learned from Using Next.js in Production
Lessons Learned from Using Next.js in ProductionLessons Learned from Using Next.js in Production
Lessons Learned from Using Next.js in Production
Panjamapong Sermsawatsri
 
Azure DevOps CI/CD For Beginners
Azure DevOps CI/CD  For BeginnersAzure DevOps CI/CD  For Beginners
Azure DevOps CI/CD For Beginners
Rahul Nath
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Maulik Shah
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
Dinesh U
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
humayunlkhan
 
React web development
React web developmentReact web development
React web development
Rully Ramanda
 
Design Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codeDesign Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID code
Paulo Gandra de Sousa
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 

What's hot (20)

Edureka-DevOps-Ebook.pdf
Edureka-DevOps-Ebook.pdfEdureka-DevOps-Ebook.pdf
Edureka-DevOps-Ebook.pdf
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
 
Virtual Container - Docker
Virtual Container - Docker Virtual Container - Docker
Virtual Container - Docker
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Universal React apps in Next.js
Universal React apps in Next.jsUniversal React apps in Next.js
Universal React apps in Next.js
 
Build Automation using Maven
Build Automation using Maven Build Automation using Maven
Build Automation using Maven
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Clean architecture with asp.net core
Clean architecture with asp.net coreClean architecture with asp.net core
Clean architecture with asp.net core
 
Inside GitHub with Chris Wanstrath
Inside GitHub with Chris WanstrathInside GitHub with Chris Wanstrath
Inside GitHub with Chris Wanstrath
 
Introduction to DevOps | Edureka
Introduction to DevOps | EdurekaIntroduction to DevOps | Edureka
Introduction to DevOps | Edureka
 
Lessons Learned from Using Next.js in Production
Lessons Learned from Using Next.js in ProductionLessons Learned from Using Next.js in Production
Lessons Learned from Using Next.js in Production
 
Azure DevOps CI/CD For Beginners
Azure DevOps CI/CD  For BeginnersAzure DevOps CI/CD  For Beginners
Azure DevOps CI/CD For Beginners
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
React web development
React web developmentReact web development
React web development
 
Design Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codeDesign Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID code
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 

Similar to Refactoring Applications using SOLID Principles

Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
Steven Smith
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing Software
Steven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
Steven Smith
 
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
Steven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
Steven 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 2016
Steven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
Steven Smith
 
Clean architecture
Clean architectureClean architecture
Clean architecture
Travis Frisinger
 
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
Steven Smith
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
Andy Butland
 
Intro to ColdBox MVC at Japan CFUG
Intro to ColdBox MVC at Japan CFUGIntro to ColdBox MVC at Japan CFUG
Intro to ColdBox MVC at Japan CFUG
Ortus Solutions, Corp
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress Applications
Taylor Lovett
 
Mcknight well built extensions
Mcknight well built extensionsMcknight well built extensions
Mcknight well built extensions
Richard McKnight
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Mayank Srivastava
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test Automation
Stephen Fuqua
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
Vibrant Technologies & Computers
 
Action-Domain-Responder: A Web-Specific Refinement of Model-View-Controller
Action-Domain-Responder: A Web-Specific Refinement of Model-View-ControllerAction-Domain-Responder: A Web-Specific Refinement of Model-View-Controller
Action-Domain-Responder: A Web-Specific Refinement of Model-View-Controller
Paul Jones
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principles
Xiaoyan Chen
 
Best practices-wordpress-enterprise
Best practices-wordpress-enterpriseBest practices-wordpress-enterprise
Best practices-wordpress-enterpriseTaylor Lovett
 

Similar to Refactoring Applications using SOLID Principles (20)

Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design 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
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
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
 
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 - 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
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 
Intro to ColdBox MVC at Japan CFUG
Intro to ColdBox MVC at Japan CFUGIntro to ColdBox MVC at Japan CFUG
Intro to ColdBox MVC at Japan CFUG
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress Applications
 
Mvc
MvcMvc
Mvc
 
Mcknight well built extensions
Mcknight well built extensionsMcknight well built extensions
Mcknight well built extensions
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test Automation
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
 
Action-Domain-Responder: A Web-Specific Refinement of Model-View-Controller
Action-Domain-Responder: A Web-Specific Refinement of Model-View-ControllerAction-Domain-Responder: A Web-Specific Refinement of Model-View-Controller
Action-Domain-Responder: A Web-Specific Refinement of Model-View-Controller
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principles
 
Best practices-wordpress-enterprise
Best practices-wordpress-enterpriseBest practices-wordpress-enterprise
Best practices-wordpress-enterprise
 

More from 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 Ardalis
Steven 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 Patterns
Steven 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 2018
Steven 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 2018
Steven Smith
 
Introducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemashIntroducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemash
Steven Smith
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
Steven Smith
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
Steven Smith
 
Decoupling with Domain Events
Decoupling with Domain EventsDecoupling with Domain Events
Decoupling with Domain Events
Steven 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 2016
Steven Smith
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
Steven 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 5
Steven Smith
 
Domain events
Domain eventsDomain events
Domain events
Steven Smith
 
My Iraq Experience
My Iraq ExperienceMy Iraq Experience
My Iraq Experience
Steven 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 MVC
Steven Smith
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
Steven Smith
 
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
Steven Smith
 
Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012
Steven Smith
 
Common design patterns (migang 16 May 2012)
Common design patterns (migang 16 May 2012)Common design patterns (migang 16 May 2012)
Common design patterns (migang 16 May 2012)
Steven Smith
 
Introducing Pair Programming
Introducing Pair ProgrammingIntroducing Pair Programming
Introducing Pair Programming
Steven Smith
 

More from 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
 
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
 
Introducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemashIntroducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemash
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
 
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
 
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
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
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
 
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
 
Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012Common asp.net design patterns aspconf2012
Common asp.net design patterns aspconf2012
 
Common design patterns (migang 16 May 2012)
Common design patterns (migang 16 May 2012)Common design patterns (migang 16 May 2012)
Common design patterns (migang 16 May 2012)
 
Introducing Pair Programming
Introducing Pair ProgrammingIntroducing Pair Programming
Introducing Pair Programming
 

Recently uploaded

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 

Recently uploaded (20)

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 

Refactoring Applications using SOLID Principles

  • 1. Refactoring Applications using SOLID Principles Steve Smith Telerik ardalis.com @ardalis www.devreach.com
  • 2.    www.devreach.com
  • 3.
  • 4. Preventive Maintenance • Refactoring – Eliminate Duplication – Simplify Design • Automated Tests – Verify correctness – Avoid regressions – Increase Confidence www.devreach.com
  • 5. Refactoring Process • Verify existing behavior • Write Characterization Tests if none exist – Find test points – Break dependencies • Apply Refactoring • Confirm existing behavior is preserved www.devreach.com
  • 6. Characterization Tests Process 1. Write a test you know will fail 2. Use the output of the failing test to determine the existing behavior to assert 3. Update the test with the new value/behavior 4. Run the test again – it should pass www.devreach.com
  • 7.
  • 8.
  • 9. SOLID Principles http://flickr.com/photos/kevinkemmerer/2772526725
  • 10. Principles of OO Design 0. Don’t Repeat Yourself (DRY) 1. Single Responsibility 2. Open/Closed 3. Liskov Substitution 4. Interface Segregation 5. Dependency Inversion www.devreach.com
  • 11.
  • 12. Don’t Repeat Repeat Yourself • Duplication in logic calls for abstraction • Duplication in process calls for automation www.devreach.com
  • 13. Common Refactorings • Replace Magic Number/String • Parameterize Method • Pull Up Field • Pull Up Method • Replace Conditional With Polymorphism • Introduce Method www.devreach.com
  • 14. Role Checks if(user.IsInRole(“Admins”) { // allow access to resource } // favor privileges over role checks // ardalis.com/Favor-Privileges-over-Role-Checks var priv = new ContentPrivilege(user, article); if(priv.CanEdit()) { // allow access } www.devreach.com
  • 15.
  • 16. Single Responsibility Principle The Single Responsibility Principle states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. Wikipedia There should never be more than one reason for a class to change. Robert C. “Uncle Bob” Martin www.devreach.com
  • 17. Example Responsibilities • Persistence • Validation • Notification • Error Handling • Logging • Class Selection / Construction • Formatting • Parsing • Mapping www.devreach.com
  • 18. Dependency and Coupling • Excessive coupling makes changing legacy software difficult • Breaking apart responsibilities and dependencies is a large part of working with existing code www.devreach.com
  • 19. Common Refactorings • Extract Class • Move Method www.devreach.com
  • 20. Heuristics and Code Smells • Visual Studio Metrics www.devreach.com
  • 21. Code Smell: Regions More on Regions: http://ardalis.com/regional-differences www.devreach.com
  • 22.
  • 23. Open / Closed Principle The Open / Closed Principle states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. Wikipedia www.devreach.com
  • 24. Open / Closed Principle Open to Extension New behavior can be added in the future Closed to Modification Changes to source or binary code are not required Dr. Bertrand Meyer originated the OCP term in his 1988 book, Object Oriented Software Construction www.devreach.com
  • 25. Common Refactorings • Extract Interface / Apply Strategy Pattern • Parameterize Method • Form Template Method www.devreach.com
  • 27. OCP Fail public bool IsSpecialCustomer(Customer c) { if(c.Country == “US” && c.Balance < 50) return false; if(c.Country == “DE” && c.Balance < 25) return false; if(c.Country == “UK” && c.Balance < 35) return false; if(c.Country == “FR” && c.Balance < 27) return false; if(c.Country == “BG” && c.Balance < 29) return false; if(c.Age < 18 || c.Age > 65) return false; if(c.Income < 50000 && c.Age < 30) return false; return true; } www.devreach.com
  • 28. OCP OK private IEnumerable<ICustomerRule> _rules; public bool IsSpecialCustomer(Customer c) { foreach(var rule in _rules) { if(rule.Evaluate(c) == false) return false; } return true; } www.devreach.com
  • 29.
  • 30. Liskov Substitution Principle The Liskov Substitution Principle states that Subtypes must be substitutable for their base types. Agile Principles, Patterns, and Practices in C# Named for Barbara Liskov, who first described the principle in 1988. www.devreach.com
  • 31. Common Refactorings • Collapse Hierarchy • Pull Up / Push Down Field • Pull Up / Push Down Method www.devreach.com
  • 32. Liskov Substitution Fail foreach(var employee in employees) { if(employee is Manager) { Helpers.PrintManager(employee as Manager); break; } Helpers.PrintEmployee(employee); } www.devreach.com
  • 33. Liskov Substitution OK foreach(var employee in employees) { employee.Print(); // or Helpers.PrintEmployee(employee); } www.devreach.com
  • 34.
  • 35. Interface Segregation Principle The Interface Segregation Principle states that Clients should not be forced to depend on methods they do not use. Agile Principles, Patterns, and Practices in C# Corollary: Prefer small, cohesive interfaces to “fat” interfaces www.devreach.com
  • 36. Common Refactorings • Extract Interface www.devreach.com
  • 37. ISP Fail (sometimes) public IRepository<T> { T GetById(int id); IEnumerable<T> List(); void Create(T item); void Update(T item); void Delete(T item); } www.devreach.com
  • 38. ISP OK (for CQRS for example) public IRepository<T> : IReadRepository<T>, IWriteRepository<T> { } public IReadRepository<T> { T GetById(int id); IEnumerable<T> List(); } public IWriteRepository<T> void Create(T item); void Update(T item); void Delete(T item); } www.devreach.com
  • 39.
  • 40. Dependency Inversion Principle High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions. Agile Principles, Patterns, and Practices in C# www.devreach.com
  • 41. Dependency Inversion Principle • Depend on Abstractions – Interfaces, not concrete types • Inject Dependencies into Classes • Structure Solution so Dependencies Flow Toward Core – Onion Architecture www.devreach.com
  • 43. Compile Time Runtime User Interface       Database www.devreach.com
  • 44. Compile Time Runtime  User Interface   Helper Class  Database www.devreach.com
  • 45. Compile Time Runtime  User Interface   Core Infrastructure IFooRepository SqlFooRepository    Database www.devreach.com
  • 47. Common Dependencies • Framework See also responsibilities: • Third Party Libraries • Persistence • Validation • Database • Notification • File System • Error Handling • Email • Logging • Web Services • Class Selection / Construction • System Resources (Clock) • Formatting • Configuration • Parsing • The new Keyword • Mapping • Static methods • Thread.Sleep • Random www.devreach.com
  • 48. Common Refactorings • Extract Class • Extract Interface / Apply Strategy Pattern • Extract Method • Introduce Service Locator / Container www.devreach.com
  • 53. Summary • Maintain / Improve Application Code • Follow DRY/SOLID Principles • Use Characterization Tests to “fix” behavior • Apply Common Refactorings • Re-run Tests After Refactorings www.devreach.com
  • 54.        www.devreach.com
  • 55. Thank You! – Благодаря! Find Me Online: Blog: http://ardalis.com Twitter: @ardalis http://facebook.com/StevenAndrewSmith www.devreach.com

Editor's Notes

  1. Note that characterization tests, though they should be automated, are often not what we would think of as unit tests, or perhaps even integration tests. For instance, you could dump a log file showing the relevant state of the application, and then use that as the basis for your characterization test by comparing against it after your changes.
  2. Avoid creating a big ball of mud system, where tracing through your code and its dependencies is like trying to unwind a tangled mess of spaghetti.
  3. A very common source of repetition of code is role checks. These often describe different scenarios in different circumstances. For instance, maybe administrators can do anything, but managers can access resources within their division, etc. Encapsulating the logic of CanView, CanCreate, CanEdit, etc. in privilege objects makes these rules explicit, easier to test, and gives them a single location to live in the application.
  4. Visual Studio can quickly analyze a project and show statistics for the classes and methods in the project. The maintainability index, cyclomatic complexity, and lines of code are all great metrics to pay attention to. The ideal maintainability index is 100, but don’t expect to hit that with any code that’s doing real work. However, you should certainly able to keep it above 50.
  5. I’m not a fan of regions. They mainly exist because at one time they were a reasonable means of hiding generated code, before we had support for partial classes and other language features to deal with this. The worst offense with regions is when they’re used within a method, like this:(click)They’re also bad when used at the class level for “standard” formatting of code, making it impossible to actually see what the code does, like this:(click)Can someone tell me what this class does?(click)I have a whole article devoted to why using regions is a bad habit, anti-pattern, code smell, whatever you prefer. It includes some survey results on the most common ways people use them as well. (click)
  6. What happens when we need to add another country?What happens when we must add another rule?How can we refactor this so this method no longer needs to change?
  7. Define a type to describe a rule. Move each rule into its own type. Create a collection of rules to apply and apply them.Pass the set of rules into the IsSpecialCustomer() method’s class (or even the method itself).
  8. Any time you find that you need to check the type of an object within a polymorphic block of code (such as a foreach), this is a sign that you are breaking LSP.
  9. This is anextemely common example of the Repository design pattern. In fact, I use this exact pattern in quite a few production applications today. There’s nothing inherently wrong with this implementation on its own. However, sometimes it does violate ISP if you need to separate Commands from Queries
  10. You can create small interfaces and compose the larger interfaces from the smaller ones if you control all of the code and you can’t simply do away with the larger interfaces. In this case, the separation of interfaces would allow us to do something like implement caching only on the read operations, and implement delayed writes using some kind of queue or message bus for the write operations.
  11. Extract interfaceImplement interface with tightly coupled original code
  12. http://en.wikipedia.org/wiki/Template_method_pattern