Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Clean code

1,413 views

Published on

Tips about Clean Code.

Published in: Software

Clean code

  1. 1. clean code There’s no problem so simple that a bad developer can’t make it complicated. Steve Bohlen Programming is the art of telling another human what one wants the computer to do. Donald Knuth 1
  2. 2. warning A quite not versed rhetorical presenter. 2
  3. 3. warning A quite not versed rhetorical presenter. Feel free to interrupt me and ask when something is not clear. 2
  4. 4. warning A quite not versed rhetorical presenter. Feel free to interrupt me and ask when something is not clear. Or something worth discussing. 2
  5. 5. what clean code stands for? Clean code is a reader-focused development style that produ- ces software that’s easy to write, read and maintain. 3
  6. 6. why it matters? Broken windows theory One broken window is all it takes to start the decline. 4
  7. 7. why it matters? Broken windows theory One broken window is all it takes to start the decline. It’s too easy to slip into the mindset of “All the rest of this code is crap, I’ll just follow suit.” 4
  8. 8. why it matters? Broken windows theory One broken window is all it takes to start the decline. It’s too easy to slip into the mindset of “All the rest of this code is crap, I’ll just follow suit.” It’s the software entropy. 4
  9. 9. why it matters? Broken windows theory One broken window is all it takes to start the decline. It’s too easy to slip into the mindset of “All the rest of this code is crap, I’ll just follow suit.” It’s the software entropy. So called: “software rot.” 4
  10. 10. the four characteristics of rotting software From the book Design Principles and Design Patterns de Robert C. Martins 5
  11. 11. 1 - rigidity It’s hard to solve simple problems. No one knows how long will take to solve them. Estimating is hard. 6
  12. 12. 2 - fragility The software breaks too often. A change in one unrelated part breaks others. Changes must be echoed in many places. 7
  13. 13. 3 - immobility It’s the inability of reusing software from other places. 8
  14. 14. 4 - viscosity Its easier to go to the hacking mode than to the design preser- vation mode. 9
  15. 15. implications O preço da gambiarra 10
  16. 16. implications O preço da gambiarra Software rot implies in frustrated developers. 10
  17. 17. implications O preço da gambiarra Software rot implies in frustrated developers. Frustrated developers implies in more rotting. 10
  18. 18. implications O preço da gambiarra Software rot implies in frustrated developers. Frustrated developers implies in more rotting. Too much rooting implies in system rewrite. 10
  19. 19. who’s fault? Managers 11
  20. 20. who’s fault? Managers NOPS 11
  21. 21. who’s fault? Managers NOPS DEVELOPERS 11
  22. 22. who’s fault? Managers NOPS DEVELOPERS The clinical analogy 11
  23. 23. solution? Good practices. Software Wisdom. Clean code! Anyone can write code a computer can understand, but profes- sional developers write code humans can understand. 12
  24. 24. literature 1. Clean code: A hand book of Agile Software craftsmanship; Robert C. Martin. 2. The pragmatical programmer; Andrew Hunt. 3. Code Complete … Lot’s more Those who do not remember the past are condemned to repeat it. Jorge Agustin Nicolas Ruiz de Santayana y Borras 13
  25. 25. some principles Dear truth always deceiving simplicity. - John Green Follow what suites you most. 14
  26. 26. some principles Dear truth always deceiving simplicity. - John Green Follow what suites you most. Obviously this is not an exhaustive list. 14
  27. 27. principle - solid Or the “first five principles” by Michael Feathers. 15
  28. 28. single responsibility principle If you can think of more than one motive for changing a class, then that class has more than one responsibility. 16
  29. 29. open close principle The interface is closed to modification - and new implementa- tion must, at least, implement that interface. 17
  30. 30. liskov substitution principle It’s possible to change subclasses without breaking the pro- gram. 18
  31. 31. interface segregation principle It’s better more interfaces than less. 19
  32. 32. dependency inversion One should depend only on abstractions. 20
  33. 33. principle - dry Don’t Repeat Yourself 21
  34. 34. principle - dry Don’t Repeat Yourself Two or more things are orthogonal if changes in one do not affect any of the others 21
  35. 35. benefits of orthogonal systems • Eliminate effects between unrelated things. • Changes are localized. • Promotes reuse. • Disease sections of code are isolated. • The result system is less fragile. • Better tested. • Not tightly to a particular vendor. 22
  36. 36. principle - law of demeter You don’t ever, ever play with your toy’s toys. 23
  37. 37. principle - law of demeter You don’t ever, ever play with your toy’s toys. If you need to change an object’s state, get the object to do it for you. Any method of an object should call only methods belonging to: • itself; • any parameters received; • any objects it creates and any directly held component objects. 23
  38. 38. principle - composite reuse One should be build only upon interfaces. Benefits • Easier to maintain (no unexpected behaviours); • Performance gain; Works flawlessly with traits. 24
  39. 39. //service user class User implements AuthenticatedUserAwareInterface, ClientAwareInterface, ServiceLocatorAwareInterface, EntityManagerAwareInterface, PluginManagerAwareInterface { use ClientAwareTrait; use AuthenticatedUserAwareTrait; use ServiceLocatorAwareTrait; use EntityManagerAwareTrait; use PluginManagerAwareTrait; 25
  40. 40. principle - design by contract Objects collaborate with each other on the basis of “mutual obli- gations and benefits”. - Bertrand Meyer 26
  41. 41. principle - design by contract Objects collaborate with each other on the basis of “mutual obli- gations and benefits”. - Bertrand Meyer Developing became the process of honoring contracts. :P 26
  42. 42. principle - design by contract Objects collaborate with each other on the basis of “mutual obli- gations and benefits”. - Bertrand Meyer Developing became the process of honoring contracts. :P Accept few and promise few. 26
  43. 43. principle - design by contract Objects collaborate with each other on the basis of “mutual obli- gations and benefits”. - Bertrand Meyer Developing became the process of honoring contracts. :P Accept few and promise few. If your contract indicates that you’ll accept anything and pro- mise the world in return, then you’ve got a lot of code to write. 26
  44. 44. principle - the scout rule Clean code is not about perfection.. It’s about honesty. 27
  45. 45. principle - the scout rule Clean code is not about perfection.. It’s about honesty. We made our best to leave the camp cleaner than we find it? 27
  46. 46. practise Tips for applying the previous principles. 28
  47. 47. functions arguments The ideal number of arguments of a function is ZERO. 29
  48. 48. functions arguments The ideal number of arguments of a function is ZERO. More than tree is unacceptable. 29
  49. 49. functions arguments The ideal number of arguments of a function is ZERO. More than tree is unacceptable. Flag arguments are ugly. They state a SRP violation. 29
  50. 50. function returns Output from function is not so good as well. 30
  51. 51. function returns Output from function is not so good as well. If functions must change a thing it must change itself. (Demeter Law) 30
  52. 52. comments - usage scenarios Put in the dock block at least the authors name. 31
  53. 53. comments - usage scenarios Put in the dock block at least the authors name. Attaching responsibility and accountability to the source code does wonders in keeping people honest. 31
  54. 54. comments - usage scenarios Put in the dock block at least the authors name. Attaching responsibility and accountability to the source code does wonders in keeping people honest. Comments serves as well to discuss the purpose and trade-offs of implementations. 31
  55. 55. comments - avoid scenarios The usual aim of comments is to express the code. 32
  56. 56. comments - avoid scenarios The usual aim of comments is to express the code. So, if they are necessary there’s a grand chance that the design smells. 32
  57. 57. comments - avoid scenarios The usual aim of comments is to express the code. So, if they are necessary there’s a grand chance that the design smells. Inaccurate comments are way worse than no comments at all. 32
  58. 58. comments - a bad case /** * * @param $title The title of the CD * @param $author The author of the CD * @param $tracks The number of tracks of the CD * */ public addCd($title, $author, int $tracks); 33
  59. 59. comments - a bad case /** * * @param $title The title of the CD * @param $author The author of the CD * @param $tracks The number of tracks of the CD * */ public addCd($title, $author, int $tracks); Clearly a DRY violation 33
  60. 60. documentation Code and documentation are different views of the same un- derlying model. Two places to edit models? DRY violation. 34
  61. 61. classes - journal metaphor (srp) Classes should be like journal articles. 35
  62. 62. classes - journal metaphor (srp) Classes should be like journal articles. In the header you get an general overview. You are able to decide if you go further or not. 35
  63. 63. classes - journal metaphor (srp) Classes should be like journal articles. In the header you get an general overview. You are able to decide if you go further or not. As you read down details increases. 35
  64. 64. classes - journal metaphor (srp) Classes should be like journal articles. In the header you get an general overview. You are able to decide if you go further or not. As you read down details increases. A journal is made of many little articles. 35
  65. 65. objects vs data structures In any good system the distinction of data structures and ob- jects is clear. 36
  66. 66. objects vs data structures In any good system the distinction of data structures and ob- jects is clear. Objects hide data and expose operations over it. 36
  67. 67. objects vs data structures In any good system the distinction of data structures and ob- jects is clear. Objects hide data and expose operations over it. Data structures expose data and have no meaningful operation. 36
  68. 68. naming Long names are generally better and simple names. Complex operations can be made simple when intermediate va- riables are used. 37
  69. 69. naming Long names are generally better and simple names. Complex operations can be made simple when intermediate va- riables are used. Need to see the source for to know what a function does? Work on names! 37
  70. 70. naming Long names are generally better and simple names. Complex operations can be made simple when intermediate va- riables are used. Need to see the source for to know what a function does? Work on names! If there’s an And in a function name it’s violating SRP. 37
  71. 71. conventions Follow a coding standard, no matter which, but all the code must follow the chosen one. Examples for php PSR2, Zend, Symphony, etc. 38
  72. 72. many little classes vs few big ones Some fear to have to browser in many files till find the right piece of code. 39
  73. 73. many little classes vs few big ones Some fear to have to browser in many files till find the right piece of code. Many classes does not imply in comprehension damage. 39
  74. 74. many little classes vs few big ones Some fear to have to browser in many files till find the right piece of code. Many classes does not imply in comprehension damage. The Many and the Few approaches both have the same amount of business logic to care of. 39
  75. 75. many little classes vs few big ones Some fear to have to browser in many files till find the right piece of code. Many classes does not imply in comprehension damage. The Many and the Few approaches both have the same amount of business logic to care of. So the question is: You prefer your tools being organized in boxes with little com- partments and good names? 39
  76. 76. many little classes vs few big ones Some fear to have to browser in many files till find the right piece of code. Many classes does not imply in comprehension damage. The Many and the Few approaches both have the same amount of business logic to care of. So the question is: You prefer your tools being organized in boxes with little com- partments and good names? Or only a compartment and all inside? 39
  77. 77. many little classes are always better than few big ones Any regular system will contain a vast quantity of logic 40
  78. 78. many little classes are always better than few big ones Any regular system will contain a vast quantity of logic The first goal of managing complexity is organizing in a way de- velopers know how to look for a certain thing, without having to worry about neighbour details. 40
  79. 79. many little classes are always better than few big ones Any regular system will contain a vast quantity of logic The first goal of managing complexity is organizing in a way de- velopers know how to look for a certain thing, without having to worry about neighbour details. We want our systems to have many little classes - not few big ones. Relates to ISP. 40
  80. 80. abuse of namespaces InventoryModelTradeStatusType.php Imagine if we extend this for a long period? 41
  81. 81. Hell! Bonus.php BonusRepository.php BonusType.php Client.php ClientRepository.php ClientSellerLevel.php Payment.php PaymentFrequency.php PaymentMode.php PaymentStatus.php Privilege.php PrivilegeRepository.php PrivilegeType.php And so on.. 42
  82. 82. Much better: InventoryModelTradeStatusType.php 43
  83. 83. remove is better than adding Perfection is attained not when there is nothing more to add, but when there is nothing more to remove. An- toine de Saint-Exupéry Don’t let existing code dictate future code. 44
  84. 84. remove is better than adding Perfection is attained not when there is nothing more to add, but when there is nothing more to remove. An- toine de Saint-Exupéry Don’t let existing code dictate future code. Be ready to refactor. 44
  85. 85. remove is better than adding Perfection is attained not when there is nothing more to add, but when there is nothing more to remove. An- toine de Saint-Exupéry Don’t let existing code dictate future code. Be ready to refactor. It may impact project schedule. 44
  86. 86. remove is better than adding Perfection is attained not when there is nothing more to add, but when there is nothing more to remove. An- toine de Saint-Exupéry Don’t let existing code dictate future code. Be ready to refactor. It may impact project schedule. The assumption is that the impact will be less than the cost of not making the change. 44
  87. 87. object calisthenics Seven code qualities premisses: • Cohesion; • Loose coupling; • No redundancy; • Encapsulation; • Testability; • Readability; • Focus; phpcs rules 45
  88. 88. 1 - one level of indentation per method; Benefits Finding bugs is much easier. If you have more than one indentation level you have more than one abstraction level. 46
  89. 89. 2 - don’t use else keyword; Else’s encourages the inclusion of more, intermediate, ifs. Use polymorphism instead. 47
  90. 90. 3 - wrap all primitives and strings; Small objects make programs more maintainable. They serves as a container for logic that otherwise would be sparse. 48
  91. 91. 4 - first class collections Any class with a collection shouldn’t contain other member va- riables. 49
  92. 92. 5 - one dot per line; Never: this ->myMemberObjectMemberObject ->myMemberObjectMemberObject ->doFoo(); Much better: this ->myMemberObjectMemberObject ->functionThatDoFooToo(); (Law of Demeter) 50
  93. 93. 6 - don’t abbreviate; Abbreviation because of exhaustive use? 51
  94. 94. 6 - don’t abbreviate; Abbreviation because of exhaustive use? DRY violation. 51
  95. 95. 6 - don’t abbreviate; Abbreviation because of exhaustive use? DRY violation. Too long names? 51
  96. 96. 6 - don’t abbreviate; Abbreviation because of exhaustive use? DRY violation. Too long names? Maybe a SRP problem. 51
  97. 97. 7 - keep all entities small; No classes over 50 lines and no packages over 10 files. 52
  98. 98. 8 - no classes with more than two instance variables. A class Name with first, middle and last name might be decom- posed to: A class Name with a Surname class and a GivenNames class. 53
  99. 99. 9 - no getters/setters/properties When you have the enough quantity of encapsulation provided from the previous rules you will never need to do any operation on the getters/setters. 54
  100. 100. testing clean code Testing code use different pattens than production code. They have different constraints. There things you will never do in production code that in testing code is allowed. Like memory and performance things. 55
  101. 101. testing clean code Testing code use different pattens than production code. They have different constraints. There things you will never do in production code that in testing code is allowed. Like memory and performance things. But never clarity things. 55
  102. 102. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? 56
  103. 103. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? To go beyond using meta data for simple preferences. 56
  104. 104. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? To go beyond using meta data for simple preferences. We want to configure and drive the application via meta data as much as possible. 56
  105. 105. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? To go beyond using meta data for simple preferences. We want to configure and drive the application via meta data as much as possible. Our goal is to think declaratively. 56
  106. 106. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? To go beyond using meta data for simple preferences. We want to configure and drive the application via meta data as much as possible. Our goal is to think declaratively. And create highly dynamic and adaptable programs. 56
  107. 107. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? To go beyond using meta data for simple preferences. We want to configure and drive the application via meta data as much as possible. Our goal is to think declaratively. And create highly dynamic and adaptable programs. How? 56
  108. 108. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? To go beyond using meta data for simple preferences. We want to configure and drive the application via meta data as much as possible. Our goal is to think declaratively. And create highly dynamic and adaptable programs. How? Program for the general case, and put the specifics somewhere else - outside the code base. 56
  109. 109. metrics Nice things to measure: • Ciclomatic complexity; • Inheritance fan-in (number of base classes); • Inheritance fan-out (number of derived modules using this one as parent); • Class coupling ratios 57
  110. 110. no magic Never buy magic! Before you commit to a framework, make sure you could write it. 58
  111. 111. no magic Never buy magic! Before you commit to a framework, make sure you could write it. Do this by actually writing something simple that does the ba- sics that you need. 58
  112. 112. no magic Never buy magic! Before you commit to a framework, make sure you could write it. Do this by actually writing something simple that does the ba- sics that you need. Make sure the magic all goes away. 58
  113. 113. conclusion Quality is a team issue. Andy hunt. Teams as a hole should not tolerate broken windows. 59
  114. 114. Obviously no one will ever do the hundred percent of what was here exposed. But if we aim for the 80% where code needs the most. We are cool. Parts not critical to performance must be clean - not optimized. 60
  115. 115. Remember… The best programmers are 28 times best than the worst ones. Robert Glass, Facts and Fallacies of Software En- gineering 61
  116. 116. Remember… The best programmers are 28 times best than the worst ones. Robert Glass, Facts and Fallacies of Software En- gineering So there’s always room for improvement. 61
  117. 117. Remember… The best programmers are 28 times best than the worst ones. Robert Glass, Facts and Fallacies of Software En- gineering So there’s always room for improvement. Thanks for all! 61

×