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

Maintainable + Extensible = Clean ... yes, Code!

Maintainable + Extensible = Clean ... yes, Code!

Clean code is like teenage sex: everyone talks about it, nobody really knows how to do it, everyone thinks everyone else is doing it, so everyone claims they are doing it... It is essential that the codes we write should be able to be understood by all. This talk will give you introduction to the principles how to write clean code that is maintainable and extensible on long terms.

29db221e8a59b06c9180725ec8ac1e75?s=128

Antonio Peric-Mazar

October 31, 2016
Tweet

More Decks by Antonio Peric-Mazar

Other Decks in Programming

Transcript

  1. Antonio Perić-Mažar 29.10.2016 - #sfcampua Maintainable + Extensible = Clean

    ... yes, Code!
  2. @antonioperic About me • Antonio Perić-Mažar, 
 mag. ing. comp.

    • CEO, Co-Founder @ Locastic • Co-Founder @ Shift Conference • Software developer, Symfony2 • Open Source Contributor • SFUGCRO
 • w: www.locastic.com • m: antonio@locastic.com • t: @antonioperic
  3. @antonioperic Locastic • We help clients create amazing web and

    mobile apps (since 2011) • design and development agency • mobile development • web development • UX/UI • Training and Consulting • Shift Conference, Symfony Croatia • www.locastic.com • t: @locastic
  4. @antonioperic Locastic

  5. @antonioperic Questions? • Who thinks he is producing good code?

    • What is bad code? • What is good code? • Do you know how to measure code quality?
  6. @antonioperic

  7. @antonioperic Note: when we asked for this code we got

    it in zip file!!! No VCS at all!
  8. @antonioperic

  9. @antonioperic

  10. @antonioperic

  11. @antonioperic

  12. @antonioperic

  13. @antonioperic This was one huge WTFn project!

  14. @antonioperic

  15. @antonioperic Code Smell!!! (Bad Code) • Use globals • Anything

    hardcoded (url, ip, etc) • Long classes or methods • Deep structures • Long and bad names • Lack of formatting • Lack of standard
  16. @antonioperic Code Smell!!! (Bad Code) • Overuse of public static

    • Too many parameters • Weird order of parameters • GOD Object (he can do everything and he knows everything) • No input validation • No comments
  17. @antonioperic Code Smell!!! (Bad Code) • Takes 1-2 sentences to

    explain • Copy-pasted - repetitive code • Never used inheritance, interface or composition • not readable • not testable
  18. @antonioperic Code Smell!!! (Bad Code) • hard to understand •

    hard to maintain • gives a headache • you don’t won’t to work on/with it
  19. @antonioperic

  20. @antonioperic Avoid being STUPID Singleton Tight coupling Untestability Premature optimization

    Indescriptive naming Duplication
  21. @antonioperic Avoid being STUPID Singleton Tight coupling Untestability Premature optimization

    Indescriptive naming Duplication
  22. @antonioperic

  23. @antonioperic But why we still doing it… • We are

    lazy • Short deadlines • Bad decisions • Fast - good - cheap • We are always the best developer ever :)
  24. @antonioperic Code has expiration date!

  25. @antonioperic Yesterday!

  26. @antonioperic Good developers are shipping! balance shipping vs good code

  27. @antonioperic Developers are evolving!

  28. @antonioperic

  29. @antonioperic Language is evolving • Frameworks (Symfony <3) • Package

    managers (composer) • Standards • PHP7
  30. @antonioperic “Any fool can write code that a computer can

    understand. Good programmers write code that humans can understand.“ Martin Fowler
  31. @antonioperic CODE

  32. @antonioperic

  33. @antonioperic Clean code • Code that doesn’t exist • KISS

    • DRY • SOLID • Don’t reinvent the wheel • Design Patterns • Testable -> Tested
  34. @antonioperic Clean code • Flexible • Maintainable • Easy to

    refactor • Readable
  35. @antonioperic Clean code is easy to understand, easy to change

    and reusable.
  36. @antonioperic

  37. @antonioperic Why we should care… • Someone else will use

    that code • You will use that code • Bad code does a lot of things but none well • You don’t write code just to be there • Maintaining should be easy • Good code save money and time
  38. @antonioperic

  39. @antonioperic If technical debt is not repaid, it can accumulate

    'interest', making it harder to implement changes later on.
  40. @antonioperic

  41. @antonioperic Guidance for better (clean) code

  42. @antonioperic #1 Naming matters • Don’t abbreviate • $string->b =

    false; • $string->bold = false; • Make code readable • Meaningful names • Improves readability • Good code should be talking to you • You should read it like a book, whitespace is important
  43. @antonioperic #1 Naming matters • Two world words variable name

    • $data, $data2 • $total, $total2, $total3
  44. @antonioperic #1 Naming matters

  45. @antonioperic #1 Naming matters • Don’t be silly!

  46. @antonioperic #1 Naming matters • Good name should explain •

    why it exist • what it does • how to use it • If you need comment for explain it, it is bad name • Class should use a noun, method a verb
  47. @antonioperic #2 Code standard • Don’t mix styles in project,

    use whitespace • Easier to navigate inside project • Less time for boarding new developer • PHP-FIG • Stick with PSR • PSR-0 autoloading • PSR-1 basing code style • PSR-2 detailed coding style
  48. @antonioperic #2 Code standard • Symfony follows the standards defined

    in the PSR-0, PSR-1, PSR-2 and PSR-4 documents. • http://symfony.com/doc/current/contributing/ code/standards.html
  49. @antonioperic #3 Use only one level of indentation per method

    • {{{ }}} try to avoid this • force single responsibility • small, simple, easier to understand • our mind model is important • separate logic blocks and complex level of indentation into methods
  50. @antonioperic #4 Don’t use else • reduce code complexity •

    early returns • use Exceptions • it reduce complex of our mind model • method should not do more then one thing • don’t use intermediate variable • use polymorphism, switch is signal for polymorphism • don’t abuse polymorphism
  51. @antonioperic #4 Don’t use else

  52. @antonioperic #5 Keep your classes/methods small • easier to test

    • do one thing, and do one thing well • all functions should return something and avoid returning NULL • keep methods small (max. 20 lines of code) • avoid side-effects • avoid global state
  53. @antonioperic #6 Use Exceptions • Use them • Make sure

    to catch them • Specify the nature of the error • throw new InvalidArgumentException(); • Don’t use special error codes
  54. @antonioperic #7 Design patterns • use them, they give you

    solution for some well known problems
  55. @antonioperic #8 Use SPL • The Standard PHP Library (SPL)

    is a collection of interfaces and classes that are meant to solve common problems. • SPL provides a set of standard datastructure, a set of iterators to traverse over objects, a set of interfaces, a set of standard Exceptions, a number of classes to work with files and it provides a set of functions like spl_autoload_register()
  56. @antonioperic #8 Use SPL • Datastructures • SplDoublyLinkedList — The

    SplDoublyLinkedList class • SplStack — The SplStack class • SplQueue — The SplQueue class • SplHeap — The SplHeap class • SplMaxHeap — The SplMaxHeap class • SplMinHeap — The SplMinHeap class • SplPriorityQueue — The SplPriorityQueue class • SplFixedArray — The SplFixedArray class • SplObjectStorage — The SplObjectStorage class
  57. @antonioperic #8 Use SPL • Iterators • AppendIterator — The

    AppendIterator class • ArrayIterator — The ArrayIterator class • CachingIterator — The CachingIterator class • CallbackFilterIterator — The CallbackFilterIterator class • DirectoryIterator — The DirectoryIterator class • EmptyIterator — The EmptyIterator class • FilesystemIterator — The FilesystemIterator class • FilterIterator — The FilterIterator class • GlobIterator — The GlobIterator class • InfiniteIterator — The InfiniteIterator class • …
  58. @antonioperic #8 Use SPL • Interfaces • Countable — The

    Countable interface • OuterIterator — The OuterIterator interface • RecursiveIterator — The RecursiveIterator interface • SeekableIterator — The SeekableIterator
  59. @antonioperic #8 Use SPL • Exceptions • BadFunctionCallException — The

    BadFunctionCallException class • BadMethodCallException — The BadMethodCallException class • DomainException — The DomainException class • InvalidArgumentException — The InvalidArgumentException class • LengthException — The LengthException class • LogicException — The LogicException class • OutOfBoundsException — The OutOfBoundsException • OutOfRangeException — The OutOfRangeException • OverflowException — The OverflowException • RangeException — The RangeException • RuntimeException — The RuntimeException • UnderflowException — The UnderflowException • UnexpectedValueException — The UnexpectedValueException class
  60. @antonioperic #9 Law of demeter (LoD) • Each unit should

    have only limited knowledge about other units: only units "closely" related to the current unit. • Each unit should only talk to its friends; don't talk to strangers. • Only talk to your immediate friends • Help you build code that is easier to test
  61. @antonioperic #9 Law of demeter

  62. @antonioperic #9 Law of Demeter

  63. @antonioperic #9 Law of demeter (LoD) • Benefits: • Keep

    object instant ion simple • Easier to mock objects • Simplify dependency graph
  64. @antonioperic #10 Comments • Good comments • Bad comments •

    PHPDoc • Don’t use comments for tracking history of changes
  65. @antonioperic #11 Use tools • PHPCS • PHP-CS-Fixer • pDepend

    (performs static code analysis) • PHPLOC (A tool for quickly measuring the size of a PHP project) • SensioLabs Insight • phpmd (mess detector) • PHPCPD (copy paste detector) • PHPDCP (dead code detector) • learn more about your IDE (PHPStorm is amazing tool)
  66. @antonioperic #12 improve yourself • read a lot of code

    • http://www.livecoding.tv/ • work in pairs • do open source - you will get a lot of free reviews from amazing developers • show your code to other developers • go to conferences • be responsive for your code
  67. @antonioperic “I live and breathe my code and my code

    is mostly the fun stuff. You know the logic, the stuff that makes cool applications, right?.“ Misko Havery
  68. @antonioperic #11 Boy-scout rule

  69. @antonioperic #12 Boy scout rule • Always check a module

    in cleaner than when you checked it out. • Always leave code in better shape then you found it
  70. @antonioperic Conclusion • Clean code is: • structured • simple

    • consistent • Use boy scout rule • Do small steps • There is no silver bullet only hard work
  71. @antonioperic References • https://cleancoders.com/ • Clean Code: A Handbook of

    Agile Software Craftsmanship, Robert C. Martin • Dotting Your I’s and Crossing Your T7s, Juliette Reinders Folmer, IPC Sprint 2015 • Your code sucks, let's fix it - By Rafael Dohms • Clean Code, Tobias Schlitt, WebSummerCamp 2016 • Google Tech Talks, Clean Code • https://www.youtube.com/watch?v=HZJxjlvBbVA, Clean Code, David Donahue • Plenty of other talks at Youtube
  72. @antonioperic Thank you! www.locastic.com antonio@locastic.com @antonioperic