12 toward solid code


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

12 toward solid code

  1. 1. Moving towardSOLID code
  2. 2. Refactoring ischanging theinternalimplementationto make it moremaintainable›  If the user sees a change, it isnt refactoring
  3. 3. Agile projectsadvocaterefactoringmercilessly
  4. 4. YAGNIYou Arent Going to Need It
  5. 5. SOLID PrinciplesSingle Responsibility PrincipleOpen Closed PrincipleLiskov Substitution PrincipleInterface Segregation PrincipleDependency Inversion Principle
  6. 6. ›  asdf
  7. 7. Single Responsibility Principle“If a class has more then one responsibility, then theresponsibilities become coupled. Changes to oneresponsibility may impair or inhibit the class’ ability tomeet the others. This kind of coupling leads to fragiledesigns that break in unexpected ways whenchanged.” - Robert C. Martin
  8. 8. Single Responsibility Principle›  A class should have one and only one reason to change›  Maybe we should call it the Single Change Reason Principle
  9. 9. Problem: We have a userinterface that reads from/writes to the database.This is not cohesive UI
  10. 10. Goal: To get the business logic out of theUI. Let the UI do what it does exclusively Business Logic UI
  11. 11. Problem: DB logic In the UI codepublic void Click(object o, EventArgs e){ var name = txtName.Text; var phone = txtPhone.Text; var db = new SqlConnection(); db.Open(); var sql ="insert into ... name ..."; var cmd = new SqlCommand(sql, db); cmd.ExecuteNonQuery();}
  12. 12. Solution: Create a Person classpublic class Person{ public string Name { get; set; } public string Phone { get; set; } public void Save() { //Write to database here //Connection, Command, ExecuteNonQuery } public Person Read(int Id) { //Read from database here //Connection, Command, ExecuteNonQuery }}
  13. 13. Problem: We still have db logicin the business logic Business Logic UI
  14. 14. Solution: Create a DB layer Business Logic Infrastructure UI
  15. 15. Create a repository classPublic class PersonRepository{ public void Save(Person) { //Write to database here } public Person Read(int Id){ //Read from database here return thePerson; }}
  16. 16. New class w/o DB logicpublic class Person{ public string Name { get; set; } public string Phone { get; set; } public void Save() { var r = new PersonRepository(); r.Save(this); } public Person Read(int Id) { var r = new PersonRepository(); return r.Read(Id); }}
  17. 17. ›  asdf
  18. 18. Open-Closed PrincipleModules that conform to the open-closed principle have twoprimary attributes.1.  They are “Open For Extension”. This means that the behavior of the module can be extended. That we can make the module behave in new and different ways as the requirements of the application change, or to meet the needs of new applications.2.  They are “Closed for Modification”. The source code of such a module is inviolate. No one is allowed to make source code changes to it. - Robert C. Martin
  19. 19. Open-Closed Principle›  Classes should be open for extension but closed for modification›  To properly change behavior, you should inherit from it and add or override functionality in the child class
  20. 20. Examples›  Physical world ›  Ryobi lawn tool›  In the Matrix ›  Visual inheritance in WinForms or WebForms ›  Custom exceptions
  21. 21. ›  sdfsd
  22. 22. Liskov Substitution Principle“If for each object o1 of type S there is an objecto2 of type T such that for all programs P definedin terms of T, the behavior of P is unchangedwhen o1 is substituted for o2 then S is a subtypeof T.” - Barbara Liskov“Functions that use pointers or references tobase classes must be able to use objects ofderived classes without knowing it.” -Robert Martin
  23. 23. Liskov Substitution Principle inreal-people words.›  Any object must be semantically similar to everything above it in the inheritance tree›  No matter how poorly named they are›  Semantically substituted, not syntactically substituted
  24. 24. Example: Bike & Motorcyclepublic interface IBicycle !{! int speed;! void Brake();! void Accelerate();!}!public class Motorcycle : IBicycle!{! public Motor Engine { get; set; }!}!
  25. 25. ›  sadf
  26. 26. Interface SegregationPrinciple“This principle deals with the disadvantages of‘fat’ interfaces. Classes that have ‘fat’interfaces are classes whose interfaces are notcohesive. In other words, the interfaces of theclass can be broken up into groups of memberfunctions. Each group serves a different set ofclients. Thus some clients use one group ofmember functions, and other clients use theother groups.” - Robert Martin
  27. 27. Interface SegregationPrinciple›  An implementing class should not be forced to depend on an interface that it doesn’t need›  Split fat interfaces up›  Very much like SRP
  28. 28. 28 Example: All-in-one printer
  29. 29. ›  sadf
  30. 30. Dependency InversionPrinciple“What is it that makes a design rigid, fragile andimmobile? It is the interdependence of themodules within that design. A design is rigid if itcannot be easily changed. Such rigidity is due tothe fact that a single change to heavilyinterdependent software begins a cascade ofchanges in dependent modules.” - Robert Martin
  31. 31. Dependency InversionPrinciple›  Depend on interfaces, not concrete implementations
  32. 32. ExampleProblem: The business classes are worthless withoutthe DB logic. Theyre too tightly coupled. Business Logic Person Infrastructure Person Repository UI
  33. 33. ›  Goal: Have a business object that maintains its state in the database Business Logic IPerson Person Repository Infrastructure Person Repository UI
  34. 34. Step 1: Create an interfacepublic interface IPersonRepository{ public void Save(); public Person Read(int Id);}public class PersonRepository : IPersonRepository{ //Same concrete implementations}
  35. 35. Step 2: Using the interfacepublic class Person{ public string Name { get; set; } public string Phone { get; set; } public void Save() { IPersonRepository r = new PersonRepository(); r.Save(this); } public Person Read(int Id) { IPersonRepository r = new PersonRepository(); return r.Read(Id); }}
  36. 36. Step 3: Pass an IPersonRepositoryinto the constructorpublic class Person{ private IPersonRepository ipr; public string Name { get; set; } public string Phone { get; set; } public Person(IPersonRepository PersonRepo) { ipr = PersonRepo; } public void Save() { ipr.Save(this); } public Person Read(int Id) { return ipr.Read(Id); }}
  37. 37. Step 4: Move the IPersonRepositoryto the Person Business Logic project Business Logic Person Infrastructure Person IPerson Repository Repository UI
  38. 38. ›  sdfgd
  39. 39. Summary›  We cant write perfect code and we shouldnt try›  It helps us to write faster if we use good design patterns and know well be back later to refactor the code›  We should use the SOLID design patterns to make more maintainable code ›  S - Each class should do one only one thing ›  O - Classes can be inherited, but not changed ›  L - Design to Interfaces, not classes ›  I - Classes shouldnt rely on things they dont use ›  D - Code should depend on interfaces, not classes