Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Code Quality Series-3 Refactoring

Code Quality Series-3 Refactoring

Slides of PHP Reboot meetup on 'Refactoring' under 'Code Quality' meetup series.

Meet up video is also uploaded to PHPReboot youtube channel (Check slide 3).

Kapil Sharma

April 14, 2018
Tweet

More Decks by Kapil Sharma

Other Decks in Technology

Transcript

  1. PHPReboot.com KapilSharma.info About me • Kapil Sharma • VP Technology

    at DJ Alexander • Working in web application development since 13+ years. • Twitter: @kapilsharmainfo • Facebook: /kapilsharmainfo • Linked in: kapilsharmainfo • Website: kapilsharma.info • Slides: speakerdeck.com/kapilsharma 2
  2. PHPReboot.com KapilSharma.info About PHP Reboot • Developers’ community in Pune,

    India. • Conducts regular meet ups • meetup.com/phpreboot • phpreboot.com • Twitter: @phpreboot • Facebook: /PHReboot • Slack: phpreboot.signup.team • Youtube: www.youtube.com/channel/ UCbLir8nYAFJ5YpcbjEFzjVw 3 Please subscribe, so that we can get custom Channel URL like youtube.com/phpreboot (Need 100 subscribers to get custom URL) Sponsored by JetBrains (IDE License) DJ Alexander (Space and snacks) Ansh Systems (Space and snacks)
  3. PHPReboot.com KapilSharma.info Why we are here? 4 Code Quality Series

    3. Refactoring 1. Object Oriented Programming 2. Solid Principles
  4. PHPReboot.com KapilSharma.info How to achieve? • Readable: Less time to

    understand what code is doing. • Simple - KISS • Single responsibility (SOLID) • Small class/methods • Consistent standards • Commonly agreed Naming convention 6 Easy to read Easy to extend • Extendability: Easy to meet new requirements without breaking existing code • DRY • Open-Close (SOLID) • Small class/method • Moduler • Continuous refactoring (consider TDD)
  5. PHPReboot.com KapilSharma.info How to fix? 7 OK I have bad

    code What’s Next? https://pixabay.com/en/baby-emphatically-sorry-to-hear-that-3257034/ Change Refactor
  6. PHPReboot.com KapilSharma.info What is Refactoring? • A change made to

    the internal structure of software to make it: • Easier to read (understand) • Easier to extend (Future changes) • Without changing observable behaviour of the software. 8
  7. PHPReboot.com KapilSharma.info Refactoring - Two step process. 9 Identify Smell

    Fix Refactoring trick Like rotten food, bad code smells Smell helps us identify bad code Identify -> Fix Know possible refactoring tricks Apply Refactoring https://pixabay.com/en/apple-worm-bitten-fruit-rotten-23484/ https://pixabay.com/en/tools-hammer-axe-garden-carpenter-42167/
  8. PHPReboot.com KapilSharma.info Bloaters 10 Code that is huge that they

    become hard to work with Long class Long method Long parameter list Data clumps Extract Method Extract class Replace temp with Query Introduce parameter object Decompose conditionals
  9. PHPReboot.com KapilSharma.info Extract Method 11 ‘What’ is easier then ‘How’

    function printOwing() { $this->printBanner(); //print details print("name: " . $this->name); print("amount " . $this->getOutstanding()); } function printOwing() { $this->printBanner(); $this->printDetails($this->getOutstanding()); } function printDetails ($outstanding) { print("name: " . $this->name); print("amount " . $outstanding); } What How
  10. PHPReboot.com KapilSharma.info Replace temp(orary variable) with query 12 $basePrice =

    $this->quantity * $this->itemPrice; if ($basePrice > 1000) return $basePrice * 0.95; else return $basePrice * 0.98; if ($this->basePrice() > 1000) return $this->basePrice() * 0.95; else return $this->basePrice() * 0.98; ... function basePrice() { return $this->quantity * $this->itemPrice; }
  11. PHPReboot.com KapilSharma.info Replace Method with Method Object 14 Long Method,

    but can’t extract due to many local variables. class Order { ... public function price() { return new PriceCalculator($this)->compute(); } } class PriceCalculator { private $primaryBasePrice; private $secondaryBasePrice; private $tertiaryBasePrice; public __construct(Order $order) { // copy relevant information from order object. ... } public function compute() { // long computation. ... } } class Order { ... public function price() { $primaryBasePrice = 10; $secondaryBasePrice = 20; $tertiaryBasePrice = 30; // long computation. ... } }
  12. PHPReboot.com KapilSharma.info Decompose Conditional 15 Extract complex part of conditions

    if ($date->before(SUMMER_START) || $date->after(SUMMER_END)) { $charge = $quantity * $winterRate + $winterServiceCharge; } else { $charge = $quantity * $summerRate; } if (notSummer($date)) { $charge = winterCharge($quantity); } else { $charge = summerCharge($quantity); }
  13. PHPReboot.com KapilSharma.info Bloaters 16 Code that is huge that they

    become hard to work with Long class Long method Long parameter list Data clumps Extract Method Extract class Replace temp with Query Introduce parameter object Decompose conditionals
  14. PHPReboot.com KapilSharma.info Short break 17 Interface Abstract class Class -

    Extend/Implement/Inherit Traits When to use what?
  15. PHPReboot.com KapilSharma.info Object Oriented Abusers 18 Switch Statement Temporary field

    Refused Bequest Alternate class with different interfaces Replace Type Code with Subclass Replace Type Code with State/ Strategy Replace Conditional with Polymorphism Replace Parameter with Explicit Methods Introduce Null Object
  16. PHPReboot.com KapilSharma.info Refused Bequest 19 Sub-class inherit only some of

    method/property of parent. Against Liskov Principle Replace inheritance with Delegation
  17. PHPReboot.com KapilSharma.info Change Preventers 20 Divergent Change Shotgun Surgery Parallel

    inheritance hierarchies Extract Class Move method Move Field Move method Move Field
  18. PHPReboot.com KapilSharma.info Dispensables 21 Dispensable = Useless Removing them will

    make code clean, efficient & easy to read. Comment Duplicate Code Lazy class Data Class Dead Code Speculative Generality
  19. PHPReboot.com KapilSharma.info Couplers 22 Feature Envy Inappropriate Intimacy Message Chains

    Middle Man Show excessive coupling A method accesses the data of another object more than its own data. One class uses the internal fields and methods of another class. $a->b()->c()->d() If a class performs only one action, delegating work to another class, why does it exist at all?
  20. PHPReboot.com KapilSharma.info Smells 23 Alternative Classes With Different Interfaces Comments

    Data Class Data Clumps Dead Code Divergent Change Duplicate Code Feature Envy Inappropriate Intimacy Incomplete Library Class Large Class Lazy Class Long Method Long Parameter List Message Chains Middle Man Parallel Inheritance Hierarchy Primitive Obsession Refused Bequest Shotgun Surgery Speculative Generality Switch Statements Temporary Field
  21. PHPReboot.com KapilSharma.info Refactoring Tricks 24 Add Parameter Change Bidirectional association

    to Unidirection Change Reference to Value Change Value To Reference Change Unidirectional association to Bidirectional Collapse Hierarchy Consolidate Conditional Expression Consolidate Duplicate Conditional Fragments Decompose Conditional Duplicate Observed Data Encapsulate Field Encapsulate Collection Extract Class Extract Interface Extract Method Extract Subclass Extract Superclass Extract Variable Form Template Method Hide Delegate Hide Method Inline Class Inline Method Inline Temp Introduce Assertion Introduce Foreign Method Introduce Local Extension Introduce Null Object Introduce Parameter Object Move Field Move Method Parameterize Method Pull up Constructor Body Pull Up Field Pull up Method Push Down Field Push Down Method Preserve Whole Object Remove Assignment to Parameters Remove Control Flag Remove Middle Man Remove Parameter Remove Setting Method Rename Method Replace conditional with Polymorphism Replace Constructor with Factory Method Replace Data Value with Object Replace Delegation with Interface Replace Error Code with Exception Replace Exception with Test Replace Inheritance with Delegation Replace Magic Number with Symbolic Constant Replace Method with Method Object Replace nested Condition with Guard Clauses Replace Parameter with Explicit Methods Replace Parameter with Method Call Replace Subclass with Fields Replace Temp with Query Replace Type Code with Class Replace Type Code with State/Strategy Self Encapsulate Field Separate Query from Modifier Split Temporary Variable Substitute Algorithm