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 - The Next Chapter


Published on

Slides for my deep dive session at Devoxx Belgium 2019.

Main concepts:
OOP, Functional Programming, Functions, Feature Envy, Design, Refactoring, Extract Method, Signatures, side effects, pure functions, programming paradigms, emotions

Would you attach your last commit to your CV:

"Sample: how I write code"?
What do others think of your code?
Writing Clean Code: an old topic, but never less important, nor challenging than today!
During the first part of this deep-dive session, we will go through the essential clean code rules, learning to detect code smells, discussing refactoring ideas and alternative designs pros/cons.

Then, after the break, we will apply what we learned in a refactoring live-coding kata, explaining 10 key practical techniques you can immediately apply in your code. By the end of the session, you will have a clear picture of what clean code means and quite a variety of ways at hand to get there.

Along the way, we will also point out the differences between procedural/oop/functional paradigms and whether they are competing or complementary, speak in detail about Extract Method, statefulness, separation by layers of abstractions, OOP, and many more.

Can't wait to share my greatest passion with you: writing professional, expressive code that is a pleasure to work with.

Published in: Software
  • Login to see the comments

Clean Code - The Next Chapter

  1. 1. The Art of Clean Code = The Next Chapter = ♦ ♦ @victorrentea ♦ This is a sequel. Check out the first episode: “The Art of Clean Code” at Devoxx Poland 2017
  2. 2. When something is painful but you can't avoid doing it… postpone it
  3. 3. When something is painful but you can't avoid doing it… delegate it
  4. 4. When something is painful but you can't avoid doing it… Do It More Often! "Bring The Pain Forward!"
  5. 5. Continuous Integration Pair Programming Continuous Refactoring Test-First "Bring The Pain Forward!" eXtreme
  6. 6. Are you Agile ?
  7. 7. Software Craftsmanship ProfessionalismTechnical Practices Code of EthicsDeliberate Practice
  8. 8. Victor Rentea Clean Code Evangelist best talks on: Lead Architect Internal Coach Software Craftsman Pair Programming, Refactoring, TDD Java Champion Founder C#
  9. 9. @victorrentea Independent Technical Trainer & Coach HibernateSpring Java 8 Architecture, DDDDesign Patterns Clean Code Unit Testing, TDD Java Performance more…Scala 240+ days1500 devs6 years 30 companies Posting daily on +Live-Trainingon 30K 3K 2K
  10. 10. …does one thing well …reads like well written prose ...was written by someone who cared ...when each method you read turns out to be pretty much what you expected Any fool can write code that a computer understands, but few programmers know how to write Introduction Clean Code … 14 Bjarne Stroustrup inventor of C++ Grady Booch inventor of UML Michael Feathers Working Effectively with Legacy Code Martin Fowler author of Refactoring Ward Cunningham inventor of Wiki, eXtreme Programmingpretty much what you expected code that a human can understand MOV AX, BX
  11. 11. VictorRentea.ro15 pretty much what you expected Unit of Measure The code is wtf/min code quality meter
  12. 12. code rot True cost of software = its maintenance Why so much !?! Cause we get slower, as the code degrades Introduction Why Clean Code ? 16 80% of the total Code smel
  13. 13. We READ 10x more time than we WRITE  Make it more readable Boy scout rule Always check in cleaner code than you found 17 Why Clean Code ?
  14. 14. Simplify* existing code without changing its external behavior Refactoring? 18 safe moves tiny steps tests Copy > Make old=useless Cut > Fix compilation Built along the way Use the IDE, Luke! * simple ≠ easy -> watch “Simple made easy” talk by Rick Hickey Write down your next commit message
  15. 15. US-134 Unit Tests US-134 Refactoring US-134 Develop 19 THE Refactoring Sprint Unit TestingCoding
  16. 16. 20 US-134 Unit Tests US-134 Refactoring US-134 Develop ⊂ ⊃ Never Separate Them
  17. 17. 21
  18. 18. VictorRentea.ro22
  19. 19. What do you do After the D-day?
  20. 20. After the D-day?
  21. 21. 26 After the D-day? Mob Refactoring 1h
  22. 22. Emotions Team 29 Clean Code is about Attitude
  23. 23. 30
  24. 24. 31 What Will You Choose? My trigger was
  25. 25. Introduction Names The power that YOU have Functions Classes Formatting & Comments 33 Agenda
  26. 26. Names 34 With Great Power Comes Great Responsibility - SpiderMan  real author is Uncle Ben
  27. 27. 36 Broca’s Area
  28. 28. Classes are nouns Customer, OrderDetails, OrderFacade Avoid meaningless names OrderInfo, OrderData vs Order Delete the interfaces ICustomerService, OrderServiceImpl 37 Delete the Interfaces OrderServiceImpl OrderDetails OrderSummary Seek 3-5 options for any name
  29. 29. … with ONE implementation in the same module 38 Delete the Interfaces except: Remoting/API your-app-api.jar Strategy® Pattern Pick implementation dynamically at runtime Dependency Inversion Implemented in lower-level modules or Decorator® tomorrow
  30. 30. 40 Have you ever blamed some code? ... then find out YOU were the author?
  31. 31. 41
  32. 32. 42 You Forget
  33. 33. 45 You try to understand some code 90% of your work life (in average)
  34. 34. 46 Then, you get it! You change only one line 2 hours 1 minute How do you feel? You try to understand some code
  35. 35. 47
  36. 36. You found a better name. 48 Make the name speak for itself It takes seconds with an IDE (and rarely fails: XMLs, reflection,…) Rename it ! OMG! It’s impossible! I CAN’T be smarter than The Elders!!
  37. 37. Keep Code Close to Domain 51 the gap
  38. 38. 52 Read it for free on:
  39. 39. 53 More Functions, Less Names!
  40. 40. 54
  41. 41.
  42. 42. Discover Value Objects privateMethod(α, β) Util1.publicHelper(α, β) VO vo = new VO(α, β); vo.method(); General-purpose? Never mocked?
  43. 43. Deepen your Domain Language
  44. 44. Introduction Names Functions Classes Formatting & Comments 61 Agenda 𝑓(𝑥)
  45. 45. A function should do one thing, it should do it well, and it should do it ONLY Functions 62 They should be Uncle Bob
  46. 46. wtf/min How small ? Functions Functions Should be Smal !! 63 5 lines* (by any means, smaller than a page of your IDE !) To be sure that they do just 1 THING What CAN you do in 5 lines ?? So you CAN find a good name for it SMALL Why so small ?!! * Actually, Uncle Bob now says 5 is too much => extract ‘till you drop
  47. 47. 66 EXTRACT METHOD
  48. 48. 67 Performance vs Clean Code Smaller methods run faster ! (get faster) Google “Just-In-Time Compiler Optimizations” Performance
  49. 49. Instead of one familiar landscape, You’re juggling with dozens of small functions You can’t even recall all their names but, The Team will thank you! 69 else for if Scared of small functions?
  50. 50. 71 Richard Feynman
  51. 51. 72 How to fully redesign well factored code? inline everything back refractor/optimize/redesign extract again
  52. 52. 73
  53. 53. Overengineering? a) does too many things ?  Try to introduce a Parameter Object/DTO/VO Max 3 parameters 74 myBadMethod("John", "Michael", "Paris", "St. Albergue"); address.setStreetName("Paris"); … myBadMethod(address); b) just passes down the args ? ?! … and see how much code it simplifies c) common params -> fields [OOP]
  54. 54. No boolean params 75 removeOrders(customer, false, true); No nullable params => 4 (usually 3) if (customer != null) {…} else {…} = laziness/fear/rush = legacy => 2 What about invalid data? ,nor Optional<>
  55. 55. Avoid returning null Throw exception Wrap it in an Optional<> Functions 76 Queue DB Defensive Programming Thoroughly check data only at the boundaries exception (corrupt data) Web Service File null with biz meaning? Optional<>
  56. 56. Entity getters returning Optional<> Game Won! 78 Customer.getMemberCard(): Optional<MemberCard> Optional<>
  57. 57. VictorRentea.ro79
  58. 58. checkCustomer(customer, order); Make them obvious wtf/min customer.setActive(true); Side Effects are Evil 80 checkAndActivateCustomer(customer, order); but necessary Because they can surprise the reader
  59. 59. do side-effects return void sendEmail(Email):void Command-Query Separation 81 setActive(true):void return results pure functions getPrice():int computePrice(movie):int More of a guideline than a rule in 1994, by Bertrand Meyer
  60. 60. No side effects No INSERTs, JMS, file, fields, WS,… Idempotent Same result for same inputs No random, time, WS, DB… Pure Functions 82 𝑓 𝑥, 𝑦 = 𝑥2 + 𝑦
  61. 61. 83 So many guidelines!
  62. 62. When I write functions, they come out long and complicated. They have lots of indenting and nested loops. They have long argument lists. The names are arbitrary, and there is duplicated code. I then massage and refine that code, splitting out functions, changing names, eliminating duplication. I don’t write them clean from the start. I don’t think anyone could. 84 ~Uncle Bob, in Clean Code
  63. 63. The Hat Metaphor 86 Writing Make it Work Cleaning Make it Readable - Kent Beck Unit Testing Crack it Copy Pasta What can I delete? How can I break it?
  64. 64. Introduction Names Functions Classes Formatting & Comments 92 Agenda
  65. 65. VictorRentea.ro93 struct(C language) Do you ever miss
  66. 66. FP =classes that expose all their state Data structures 94 public class ImmutableStruct { private final String firstName; private final String lastName; public ImmutableStruct( String first, String last) { this.firstName = first; this.lastName = last; // validation ... } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } We Immutable Objects: - If created valid, remain so - Easier to debug - Thread safe - Safe as keys in Tree*/Hash* struct ≈ Value Object Pure Function is what you want to do, Side Effects are what you’re being paid to do. ~ “Functional Programming in 40 Minutes” by Russ Olsen at GOTO’18
  67. 67. =classes that expose all their state Data structures 97 public class PhoneBookEntryDTO { private String firstName; private String lastName; private String phoneNumber; public String getFirstName() { return firstName; } public void setFirstName(String first) { this.firstName = first; } public String getLastName() { … } public void setLastName(…) { … } public String getPhoneNumber() { … } public void setPhoneNumber(…) { … } } public class ImmutableStruct { private final String firstName; private final String lastName; public ImmutableStruct( String first, String last) { this.firstName = first; this.lastName = last; // validation ... } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } public class PhoneBookEntryDTO { public String firstName; public String lastName; public String phoneNumber; } ≈ struct "Object-Oriented Assembly Language"
  68. 68. VictorRentea.ro98 OOP
  69. 69. Expose Behavior, not data Data is an implementation detail OOP 99 car.engineStarted=true car.setEngineStarted(true) car.startEngine() Information Hiding Even when asked car.getGasolineInLiters() car.getPercentageFuelLeft() car.getEstimatedRemainingKm() Implementation can evolve without breaking your clients
  70. 70. 100 Protect client code from future changes in implem of a Library or (mini) Framework mycorp-commons- .jar Decompose complex logic into separate objects Divide-et-impera on Complexity API CsvWriter
  71. 71. 101 But at work we don’t do much OOP, do we ? In our Enterprise Apps, we write procedural code
  72. 72. VictorRentea.ro102 Existing procedures. (usually) We automate existing business processes. Procedural Code
  73. 73. VictorRentea.ro103 Lots Procedural Code and lots and lots and lots and lots of it… How do we organize it, to Keep It Short & Simple ?
  74. 74. VictorRentea.ro104 Procedural Code We distribute logic in many classes: Keep It Short & Simple Classes as containers of logic (in enterprise applications) !!
  75. 75. 105 Procedural OOP FP
  76. 76. 106
  77. 77. VictorRentea.ro107 Icon made by ‘freepik’ from Procedural FP OOP Encapsulate State Decompose Side-Effects Concise Scalable Debuggable
  78. 78. 110 Introduction Names Functions Classes Formatting & Comments Agenda
  79. 79. 112
  80. 80. 113
  81. 81. 114 You're not Neo It’s all about Team Work WAKE UP!
  82. 82. VictorRentea.ro115 Don’t Code! Communicate !
  83. 83. Respect your readers Details matter: 10x more reading, remember ? Write Literature The simplest code that works. Never obfuscate Don’t Code! Communicate ! Simplicity is the ultimate sophistication - Leonardo da Vinci
  84. 84. 117
  85. 85. 118 Master your IDE Sharpen reflexes for real races Learn those shortcuts !  Key Promoter X (IDEA plugin)
  86. 86. 120 When it's red, yellow, blue or gray, Alt-Enter will save your day. Ctrl-1 Ctrl-.
  87. 87. Comments 123
  88. 88. public List<int[]> getFlaggedCells(){ List<int[]> flaggedCells = new A…L…<…>(); for (int[] cell : gameBoard) { boolean isFlagged= cell[STATUS]==FLAGGED; if (isFlagged) flaggedCells.add(cell); } return flaggedCells; } Readable Constants - Instead of magic numbers Explanatory Variables - Name intermediary results - if (multiline && (conditions || formulas)) Explanatory Methods - "Encapsulate Conditionals" Rename & Extract - descriptive names 124 public List<int[]> getCells() { List<int[]> list1 = new ArrayList<int[]>(); for (int[] x : theList) if (x[0] == 4) list1.add(x); return list1; } public List<Cell> getFlaggedCells(){ List<Cell> flaggedCells = new A…L…<Cell>(); for (Cell cell : gameBoard) { if (cell.isFlagged()) flaggedCells.add(cell); } return flaggedCells; }
  89. 89. Opinions? 129 // Register user // Loop over all entries and remove nulls // Avoids memory leak DUH!!extract
  90. 90. VictorRentea.ro142 Clean Code + Java8 Try some lib? jOOL, vavr,… For more, check-out the screen cast of my Clean Lambdas workshop at Voxxed Bucharest 2017, on my website 
  91. 91. Pair Programming 143 Peer Review!
  92. 92. VictorRentea.ro144 Peer Review! Pair Programming
  93. 93. 147 Introduction Names Functions Classes Formatting & Comments Java 8+ Agenda
  94. 94. Key Points 148 Introduction Names Functions Classes Formatting & Comments Clean Lambdas Agenda Refine Expressive Names Stop Refactor = Start Legacy Short methods Structs, Objects or Logic Containers ? Comments are Failures. Expressive code. Pair Programming is the way
  95. 95. 149 What can I do to make refactor happen each day in my team? Shamelessly taken from the Effective Refactoring workshop of my friend Wlodek 
  96. 96. 150 How to apply all this in my legacy code ?? Where can I read more ? LET’S PRACTICE !!! Pragmatic + Professional ©
  97. 97. 152
  98. 98. 153 Clean Code Requires Discipline
  99. 99. 154 Coding Kata
  100. 100. 155 Coding Kata No rush Safe environment Perfection Reflect on HOW you work
  101. 101. 156 Pair Programming Refactoring TDD
  102. 102. 157 Topics Refactoring TDD Legacy Code Time 1-1.5 h timeboxed People 4-10 Coding Dojo Synthetic Exercises NOT prod code!!
  103. 103. 159 Blamestorming Retro Some learning key points
  104. 104. Rename & Extract Method
  105. 105. When you cannot find a satisfying name for a variable or a method, Choose a Welsh one. You won't forget to change it later - Mario Fusco
  106. 106. Extract Method Selection to Extract variable expression Extract Variables to generify/reuse … then extract method …then inline var back Expand Selection for less parameters
  107. 107. Feature Envy method(α, …) α.method(…) “Move” refactor “Keep Behavior next to State”[OOP]
  108. 108. 3. Ctrl- 2. Revert 1. Reader Most Powerful Forces in Universe
  109. 109. Do you love switches?
  110. 110. Switch Hygiene Rules: is the only instruction in a method default: throw new One-line per case : return func(); : func(); break; Coming soon: return switch … JEP 325: Switch Expressions Java 14… soon…  JDD
  111. 111. I'm available a statement of seniority I use both hemispheres Tough meetings? Abused estimates? Purpose of code:--Uncle Bob 1. Maintainable 2. Does its job! Functional Party Activist Stay into The Light Trainings, talks, goodies @VictorRentea Follow me for quality posts: Clean Code needs strength and determination Thank You! me take 1 sticker or shortcuts sheet + unity Speaking Romanian? join me Download and customize from Hunt me for questions! This talk was a sequel of the first episode: “The Art of Clean Code” at Devoxx Poland 2017