12 toward solid code
Upcoming SlideShare
Loading in...5
×
 

12 toward solid code

on

  • 475 views

 

Statistics

Views

Total Views
475
Views on SlideShare
475
Embed Views
0

Actions

Likes
0
Downloads
11
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

12 toward solid code 12 toward solid code Presentation Transcript

  • Moving towardSOLID code
  • Refactoring ischanging theinternalimplementationto make it moremaintainable›  If the user sees a change, it isnt refactoring
  • Agile projectsadvocaterefactoringmercilessly
  • YAGNIYou Arent Going to Need It
  • SOLID PrinciplesSingle Responsibility PrincipleOpen Closed PrincipleLiskov Substitution PrincipleInterface Segregation PrincipleDependency Inversion Principle
  • ›  asdf
  • 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
  • Single Responsibility Principle›  A class should have one and only one reason to change›  Maybe we should call it the Single Change Reason Principle
  • Problem: We have a userinterface that reads from/writes to the database.This is not cohesive UI
  • Goal: To get the business logic out of theUI. Let the UI do what it does exclusively Business Logic UI
  • 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();}
  • 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 }}
  • Problem: We still have db logicin the business logic Business Logic UI
  • Solution: Create a DB layer Business Logic Infrastructure UI
  • 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; }}
  • 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); }}
  • ›  asdf
  • 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
  • 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
  • Examples›  Physical world ›  Ryobi lawn tool›  In the Matrix ›  Visual inheritance in WinForms or WebForms ›  Custom exceptions
  • ›  sdfsd
  • 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
  • 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
  • Example: Bike & Motorcyclepublic interface IBicycle !{! int speed;! void Brake();! void Accelerate();!}!public class Motorcycle : IBicycle!{! public Motor Engine { get; set; }!}!
  • ›  sadf
  • 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
  • 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 Example: All-in-one printer
  • ›  sadf
  • 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
  • Dependency InversionPrinciple›  Depend on interfaces, not concrete implementations
  • ExampleProblem: The business classes are worthless withoutthe DB logic. Theyre too tightly coupled. Business Logic Person Infrastructure Person Repository UI
  • ›  Goal: Have a business object that maintains its state in the database Business Logic IPerson Person Repository Infrastructure Person Repository UI
  • Step 1: Create an interfacepublic interface IPersonRepository{ public void Save(); public Person Read(int Id);}public class PersonRepository : IPersonRepository{ //Same concrete implementations}
  • 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); }}
  • 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); }}
  • Step 4: Move the IPersonRepositoryto the Person Business Logic project Business Logic Person Infrastructure Person IPerson Repository Repository UI
  • ›  sdfgd
  • 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