Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Follow me at twitter.com/ardalisRefactoring Applicationsusing SOLID PrinciplesSteve SmithTelerikardalis.com @ardalis
Follow me at twitter.com/ardalisMore on this topicComing Soon: Refactoring Fundamentals
Follow me at twitter.com/ardalis
Follow me at twitter.com/ardalisPreventive Maintenance• Refactoring– Eliminate Duplication– Simplify Design• Automated Tes...
Follow me at twitter.com/ardalisRefactoring Process• Verify existing behavior• Write Characterization Tests if none exist–...
Follow me at twitter.com/ardalisCharacterization TestsProcess1. Write a test you know will fail2. Use the output of the fa...
S O L I DPrincipleshttp://flickr.com/photos/kevinkemmerer/2772526725
Follow me at twitter.com/ardalisPrinciples of OO Design0. Don’t Repeat Yourself (DRY)1. Single Responsibility2. Open/Close...
Follow me at twitter.com/ardalisDon’t RepeatRepeat Yourself• Duplication in logic calls for abstraction• Duplication in pr...
Follow me at twitter.com/ardalisCommon Refactorings• Replace Magic Number/String• Parameterize Method• Pull Up Field• Pull...
Follow me at twitter.com/ardalisRole Checksif(user.IsInRole(“Admins”){// allow access to resource}// favor privileges over...
Follow me at twitter.com/ardalisSingle Responsibility PrincipleThe Single Responsibility Principle states that every objec...
Follow me at twitter.com/ardalisExample Responsibilities• Persistence• Validation• Notification• Error Handling• Logging• ...
Follow me at twitter.com/ardalisDependency and Coupling• Excessive coupling makes changinglegacy software difficult• Break...
Follow me at twitter.com/ardalisCommon Refactorings• Extract Class• Move Method
Follow me at twitter.com/ardalisHeuristics and Code Smells• Visual Studio Metrics
Follow me at twitter.com/ardalisCode Smell: RegionsMore on Regions: http://ardalis.com/regional-differences
Follow me at twitter.com/ardalisOpen / Closed PrincipleThe Open / Closed Principle states that software entities(classes, ...
Follow me at twitter.com/ardalisOpen / Closed PrincipleOpen to ExtensionNew behavior can be added in the futureClosed to M...
Follow me at twitter.com/ardalisCommon Refactorings• Extract Interface / Apply Strategy Pattern• Parameterize Method• Form...
Follow me at twitter.com/ardalisOCP Fail
Follow me at twitter.com/ardalisOCP OK
Follow me at twitter.com/ardalisOCP Failpublic bool IsSpecialCustomer(Customer c){if(c.Country == “US” && c.Balance < 50) ...
Follow me at twitter.com/ardalisOCP OKprivate IEnumerable<ICustomerRule> _rules;public bool IsSpecialCustomer(Customer c){...
Follow me at twitter.com/ardalisLiskov Substitution PrincipleThe Liskov Substitution Principle states thatSubtypes must be...
Follow me at twitter.com/ardalisCommon Refactorings• Collapse Hierarchy• Pull Up / Push Down Field• Pull Up / Push Down Me...
Follow me at twitter.com/ardalisLiskov Substitution Failforeach(var employee in employees){if(employee is Manager){Helpers...
Follow me at twitter.com/ardalisLiskov Substitution OKforeach(var employee in employees){employee.Print();// orHelpers.Pri...
Follow me at twitter.com/ardalisInterface Segregation PrincipleThe Interface Segregation Principle states thatClients shou...
Follow me at twitter.com/ardalisCommon Refactorings• Extract Interface
Follow me at twitter.com/ardalisISP Fail (sometimes)public IRepository<T>{T GetById(int id);IEnumerable<T> List();void Cre...
Follow me at twitter.com/ardalisISP OK (for CQRS for example)public IRepository<T> : IReadRepository<T>,IWriteRepository<T...
Follow me at twitter.com/ardalisDependency Inversion PrincipleHigh-level modules should not depend on low-levelmodules. Bo...
Follow me at twitter.com/ardalisDependency Inversion Principle• Depend on Abstractions– Interfaces, not concrete types• In...
Follow me at twitter.com/ardalisApplication Layers
Follow me at twitter.com/ardalisUser InterfaceDatabaseCompile TimeRuntime
Follow me at twitter.com/ardalisUser InterfaceDatabaseCompile TimeRuntimeHelper Class
Follow me at twitter.com/ardalisUser InterfaceDatabaseCompile TimeRuntimeCoreIFooRepositoryInfrastructureSqlFooRepos...
Follow me at twitter.com/ardalisDIP “Onion” Architecture
Follow me at twitter.com/ardalisCommon Dependencies• Framework• Third Party Libraries• Database• File System• Email• Web S...
Follow me at twitter.com/ardalisCommon Refactorings• Extract Class• Extract Interface / Apply Strategy Pattern• Extract Me...
Follow me at twitter.com/ardalisDIP Fail
Follow me at twitter.com/ardalisSome Improvement (Façade)
Follow me at twitter.com/ardalisDIP OK (Strategy)
Follow me at twitter.com/ardalisDIP OK (Strategy)
Follow me at twitter.com/ardalisSummary• Maintain / Improve Application Code• Follow DRY/SOLID Principles• Use Characteriz...
Follow me at twitter.com/ardalis
Follow me at twitter.com/ardalis
Follow me at twitter.com/ardalisThank You!Find Me Online:Blog: http://ardalis.comTwitter: @ardalishttp://facebook.com/Stev...
Follow me at twitter.com/ardalis
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
Refactoring with SOLID Principles (FalafelCon 2013)
Upcoming SlideShare
Loading in …5
×

Refactoring with SOLID Principles (FalafelCon 2013)

5,311 views

Published on

We’ve all heard about well-designed software projects, where things aren’t (yet) a big ball of mud that’s painful to work with, but many of us aren’t lucky enough to work on these. Nor is it an option for us to get to start a brand new “greenfield” project, where we can leave behind the legacy of spaghetti code and technical debt our current project might have.


But there is hope! By applying refactoring steps based on SOLID principles of object oriented design, we can reduce the technical debt of our existing application, improve our code quality, and hopefully make our application more enjoyable and productive to work with.


In this session, we’ll briefly introduce the SOLID principles and several design patterns, and then we’ll apply these principles and patterns by improving the design of an existing application through several refactoring steps.

Published in: Technology
  • Sex in your area is here: ❶❶❶ http://bit.ly/2ZDZFYj ❶❶❶
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Dating direct: ❤❤❤ http://bit.ly/2ZDZFYj ❤❤❤
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Refactoring with SOLID Principles (FalafelCon 2013)

  1. 1. Follow me at twitter.com/ardalisRefactoring Applicationsusing SOLID PrinciplesSteve SmithTelerikardalis.com @ardalis
  2. 2. Follow me at twitter.com/ardalisMore on this topicComing Soon: Refactoring Fundamentals
  3. 3. Follow me at twitter.com/ardalis
  4. 4. Follow me at twitter.com/ardalisPreventive Maintenance• Refactoring– Eliminate Duplication– Simplify Design• Automated Tests– Verify correctness– Avoid regressions– Increase Confidence
  5. 5. Follow me at twitter.com/ardalisRefactoring Process• Verify existing behavior• Write Characterization Tests if none exist– Find test points– Break dependencies• Apply Refactoring• Confirm existing behavior is preserved
  6. 6. Follow me at twitter.com/ardalisCharacterization TestsProcess1. Write a test you know will fail2. Use the output of the failing test todetermine the existing behavior to assert3. Update the test with the newvalue/behavior4. Run the test again – it should pass
  7. 7. S O L I DPrincipleshttp://flickr.com/photos/kevinkemmerer/2772526725
  8. 8. Follow me at twitter.com/ardalisPrinciples of OO Design0. Don’t Repeat Yourself (DRY)1. Single Responsibility2. Open/Closed3. Liskov Substitution4. Interface Segregation5. Dependency Inversion
  9. 9. Follow me at twitter.com/ardalisDon’t RepeatRepeat Yourself• Duplication in logic calls for abstraction• Duplication in process calls forautomation
  10. 10. Follow me at twitter.com/ardalisCommon Refactorings• Replace Magic Number/String• Parameterize Method• Pull Up Field• Pull Up Method• Replace Conditional With Polymorphism• Introduce Method
  11. 11. Follow me at twitter.com/ardalisRole Checksif(user.IsInRole(“Admins”){// allow access to resource}// favor privileges over role checks// ardalis.com/Favor-Privileges-over-Role-Checksvar priv = new ContentPrivilege(user, article);if(priv.CanEdit()){// allow access}
  12. 12. Follow me at twitter.com/ardalisSingle Responsibility PrincipleThe Single Responsibility Principle states that every objectshould have a single responsibility, and thatresponsibility should be entirely encapsulated by theclass.WikipediaThere should never be more than one reason for a class tochange.Robert C. “Uncle Bob” Martin
  13. 13. Follow me at twitter.com/ardalisExample Responsibilities• Persistence• Validation• Notification• Error Handling• Logging• Class Selection / Construction• Formatting• Parsing• Mapping
  14. 14. Follow me at twitter.com/ardalisDependency and Coupling• Excessive coupling makes changinglegacy software difficult• Breaking apart responsibilities anddependencies is a large part of workingwith existing code
  15. 15. Follow me at twitter.com/ardalisCommon Refactorings• Extract Class• Move Method
  16. 16. Follow me at twitter.com/ardalisHeuristics and Code Smells• Visual Studio Metrics
  17. 17. Follow me at twitter.com/ardalisCode Smell: RegionsMore on Regions: http://ardalis.com/regional-differences
  18. 18. Follow me at twitter.com/ardalisOpen / Closed PrincipleThe Open / Closed Principle states that software entities(classes, modules, functions, etc.) should be open forextension, but closed for modification.Wikipedia
  19. 19. Follow me at twitter.com/ardalisOpen / Closed PrincipleOpen to ExtensionNew behavior can be added in the futureClosed to ModificationChanges to source or binary code are not requiredDr. Bertrand Meyer originated the OCP term in his 1988book, Object Oriented Software Construction
  20. 20. Follow me at twitter.com/ardalisCommon Refactorings• Extract Interface / Apply Strategy Pattern• Parameterize Method• Form Template Method
  21. 21. Follow me at twitter.com/ardalisOCP Fail
  22. 22. Follow me at twitter.com/ardalisOCP OK
  23. 23. Follow me at twitter.com/ardalisOCP Failpublic 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;}
  24. 24. Follow me at twitter.com/ardalisOCP OKprivate IEnumerable<ICustomerRule> _rules;public bool IsSpecialCustomer(Customer c){foreach(var rule in _rules){if(rule.Evaluate(c) == false) return false;}return true;}
  25. 25. Follow me at twitter.com/ardalisLiskov Substitution PrincipleThe Liskov Substitution Principle states thatSubtypes must be substitutable for theirbase types.Agile Principles, Patterns, and Practices inC#Named for Barbara Liskov, who firstdescribed the principle in 1988.
  26. 26. Follow me at twitter.com/ardalisCommon Refactorings• Collapse Hierarchy• Pull Up / Push Down Field• Pull Up / Push Down Method
  27. 27. Follow me at twitter.com/ardalisLiskov Substitution Failforeach(var employee in employees){if(employee is Manager){Helpers.PrintManager(employee as Manager);break;}Helpers.PrintEmployee(employee);}
  28. 28. Follow me at twitter.com/ardalisLiskov Substitution OKforeach(var employee in employees){employee.Print();// orHelpers.PrintEmployee(employee);}
  29. 29. Follow me at twitter.com/ardalisInterface Segregation PrincipleThe Interface Segregation Principle states thatClients should not be forced to depend onmethods they do not use.Agile Principles, Patterns, and Practices in C#Corollary:Prefer small, cohesive interfaces to “fat” interfaces
  30. 30. Follow me at twitter.com/ardalisCommon Refactorings• Extract Interface
  31. 31. Follow me at twitter.com/ardalisISP Fail (sometimes)public IRepository<T>{T GetById(int id);IEnumerable<T> List();void Create(T item);void Update(T item);void Delete(T item);}
  32. 32. Follow me at twitter.com/ardalisISP 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);}
  33. 33. Follow me at twitter.com/ardalisDependency Inversion PrincipleHigh-level modules should not depend on low-levelmodules. Both should depend on abstractions.Abstractions should not depend on details. Detailsshould depend on abstractions.Agile Principles, Patterns, and Practices in C#
  34. 34. Follow me at twitter.com/ardalisDependency Inversion Principle• Depend on Abstractions– Interfaces, not concrete types• Inject Dependencies into Classes• Structure Solution so Dependencies FlowToward Core– Onion Architecture
  35. 35. Follow me at twitter.com/ardalisApplication Layers
  36. 36. Follow me at twitter.com/ardalisUser InterfaceDatabaseCompile TimeRuntime
  37. 37. Follow me at twitter.com/ardalisUser InterfaceDatabaseCompile TimeRuntimeHelper Class
  38. 38. Follow me at twitter.com/ardalisUser InterfaceDatabaseCompile TimeRuntimeCoreIFooRepositoryInfrastructureSqlFooRepository
  39. 39. Follow me at twitter.com/ardalisDIP “Onion” Architecture
  40. 40. Follow me at twitter.com/ardalisCommon Dependencies• Framework• Third Party Libraries• Database• File System• Email• Web Services• System Resources (Clock)• Configuration• The new Keyword• Static methods• Thread.Sleep• RandomSee also responsibilities:• Persistence• Validation• Notification• Error Handling• Logging• Class Selection /Construction• Formatting• Parsing• Mapping
  41. 41. Follow me at twitter.com/ardalisCommon Refactorings• Extract Class• Extract Interface / Apply Strategy Pattern• Extract Method• Introduce Service Locator / Container
  42. 42. Follow me at twitter.com/ardalisDIP Fail
  43. 43. Follow me at twitter.com/ardalisSome Improvement (Façade)
  44. 44. Follow me at twitter.com/ardalisDIP OK (Strategy)
  45. 45. Follow me at twitter.com/ardalisDIP OK (Strategy)
  46. 46. Follow me at twitter.com/ardalisSummary• Maintain / Improve Application Code• Follow DRY/SOLID Principles• Use Characterization Tests to “fix”behavior• Apply Common Refactorings• Re-run Tests After (and during)Refactorings
  47. 47. Follow me at twitter.com/ardalis
  48. 48. Follow me at twitter.com/ardalis
  49. 49. Follow me at twitter.com/ardalisThank You!Find Me Online:Blog: http://ardalis.comTwitter: @ardalishttp://facebook.com/StevenAndrewSmith
  50. 50. Follow me at twitter.com/ardalis

×