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

Clean PHP

Clean PHP

Talk based on "Clean Code" book contents by Robert C. Martin (aka Uncle Bob), with focus on its initial chapters accessible for any level of experience programmers. With some samples in PHP.

Talk for Ciklum presented on February 22nd, 2018.
https://www.meetup.com/es-ES/Ciklum-Spain-IT-expertise-sharing/events/247378813/

Francisco M. González

February 22, 2018
Tweet

More Decks by Francisco M. González

Other Decks in Technology

Transcript

  1. 2 Welcome Franci González • Father (3) • Comic-book collector

    (6k) • Malagueño • Sofware crafsman at Ciklum
  2. 3 Table of contents • What’s clean code? • Naming

    • Functions • Comments • Code style
  3. 5 About Clean Code Any fool can write code that

    a computer can understand. Good programmers write code that humans can understand. - Martin Fowler What’s Clean Code
  4. 8 What’s not clean code? Don’t describe what it does

    It’s hard to understand It’s hard to modify What’s Clean Code
  5. 9 What’s Clean Code Horrible hack vs. Temporal solution Horrible

    hack which I didn’t write Horrible hack which I wrote
  6. 10 What’s Clean Code Bad structure vs. Complex architecture Bad

    structure which I didn’t design Bad structure which I designed
  7. 11 What’s Clean Code Needs a refactor vs. Clean solution

    It works but I don’t understand it It works and I understand it
  8. 12 How is good code? • Readable • Robust •

    Reusable • Efficient What’s Clean Code
  9. 13 How does clean code looks like? • Elegant •

    Efficient • Simple and straight forward • Readable as prose • Carefully done • Small What’s Clean Code
  10. 14 About respect Always code as if the guy who

    ends up maintaining your code will be a violent psychopath who knows where you live. - John F. Woods What’s Clean Code
  11. 16

  12. 18 Everything is about Naming • Classes • Namespaces •

    Functions • Variables • Files • Directories • … Naming
  13. 25 Avoid encodings and type sufixes IAccount (interface) $pWriter (pointer)

    $bActive (boolean) $eStatus (enum) $m_size (member attribute) _save() (private method) Naming
  14. 26 Some name tips Classes and instances: - Names -

    No verbs - No actions Methods: - Verbs as actions - Accesors: get - Mutators: set - Predicates: is /has Naming
  15. 29 Names according to the scope foreach ($items as $item)

    { ... $item→doSomething(); ... } Naming
  16. 30 Names according to the scope try { ... }

    catch (Exception $e) { log($e->getMessage()); } Naming
  17. 31 Names according to the scope Private: • tryProcessInstructions() •

    closeServiceInSeparateThread() Naming Public: • open() • close() • save()
  18. 36

  19. 39 Two basic rules about functions 1.They should be small

    2.They should be smaller! Functions
  20. 40 Do one thing 1. Just one thing 2. Do

    it well 3. Do one thing and one thing only Functions
  21. 41 Functions should… • Do something: Change a status, as

    a statement. • Return something: A query. Functions
  22. 42 Functions should… • Do something: Change a status, as

    a statement. • Return something: A query. Never both. Remember: Do one thing. Functions
  23. 43 Extract till you drop • If you can extract

    part of your function to another one, you MUST do it. It’s doing more than one thing • Extract until you can’t extract more • Extract until you drop Functions
  24. 44 Use the same abstraction level // High level return

    view(‘template’); // Medium level echo view(‘child-template’)→render(); // Low level echo ‘<br/>’; Functions
  25. 45 Descriptive names • Don’t be afraid of using long

    names • Long and descriptive names are better than short and misleading • Try and error. Don’t hesitate to rename until you feel confident with it Functions
  26. 46 Arguments • Niladic. Ideal • Monadic or Diadic. •

    Triadic. Avoid if possible. • Polyadic. They require a clear reason, but even though don’t use it • Don’t use flag arguments Functions
  27. 47 Outputs • Don’t return more than one output •

    Better throw exceptions than error codes • Extract try/catch blocks Functions
  28. 52 Comments are errors • You ignore them while reading

    • Hint of bad naming • The good comment is the one you don’t write • They should be rare. Highlighted by the IDE • Misleading and source of errors Comments
  29. 53 The value of comments • The value of a

    comment is directly proportional to the distance between the comment and the code • Never trust comments with complex formatting • Don’t include redundant information Comments
  30. 54 About Comments Incorrect documentation is ofen worse than no

    documentation. - Bertrand Meyer Comments
  31. 55 Good comments • Legal purposes (no way to avoid

    them) • Format (e.g. a regular expression) // format matched kk:mm:ss EEE, MMM dd, yyyy $pattern = “\\d*:\\d*:\\d* \\w*, \\w* \\d*, \\d*” Comments
  32. 56 Bad comments /* The logger class */ protected $logger;

    /* The version */ public $version; Comments
  33. 57 Bad comments /** * @param $item The item to

    be added * @param $position The position to be added */ public function addItem($item, $position = 0); Comments
  34. 58 Bad comments /** * 11/12/2010 - Added the colour

    feature * 03/02/2011 - removed deprecated function * 07/02/2011 - Fixed bug in addPoints * … Comments
  35. 62 About Comments You should always write your code as

    if comments didn't exist. - Jeff Atwood Comments
  36. 65 Why should we use a code style? • Code

    style is more persistent than code itself • Easier to modify and refactor • More readable • It’s a team’s agreement • It’s a communication tool Code style
  37. 66 Enhance ytilibadaer • Enhance readability • Enhance your confidence

    • You feel more reliable • Less feeling of code ownership Code style
  38. 67 Choose your code style (as a team) Code style

    namespace Foo; public class Bar { ... } namespace Foo; public class Bar { ... }
  39. 68 Choose your code style (as a team) Code style

    $items = […]; $items = array(…);
  40. 69 Standards Code style • What’s PSR? PHP Standards Recommendation

    PSR-1 Basic Coding Standard PSR-2 Coding Style Guide PSR-12 Extended Coding Style Guide
  41. 70 Other standards Code style • Zend • Symfony •

    PEAR • Wordpress • Drupal • …
  42. 72 Tools (editorconfig) • Set up a custom .editorconfig file

    for your project • Most IDEs support editorconfig Code style
  43. 74 Naming • Declare intention • Avoid misinformation • Avoid

    old-fashioned encodings • Pronounceables and searchables • Remember the scope rule Summary
  44. 75 Functions • Small • Smaller • Descriptive names •

    Do one thing. Statements and queries • Extract till you drop Summary
  45. 77 Code style • Help maintenance • It’s a team’s

    agreement • Choose a standard • Add it to your CI Summary
  46. 78 Check if your code is clean • Make your

    colleagues read it and give their opinion • Come back to your code 3-4 weeks afer you’ve forgotten it, and see if you can still understand it • Publish it, if you can • Show your code to programmers whose opinion you respect Summary