(This page has no text content)
(This page has no text content)
(This page has no text content)
Clean Code: A Handbook of Agile Software Craftsmanship Second Edition Robert C. Martin A NOTE FOR EARLY RELEASE READERS With Early Release eBooks, you get books in their earliest form—the author’s raw and unedited content as they write— so you can take advantage of these technologies long before the official release of these titles. If you have comments about how we might improve the content and/or examples in this book, or if you notice missing material within this title, please reach out to Pearson at PearsonITAcademics@pearson.com
Contents Foreword Introduction Introduction (from Long Ago) Chapter 1: Clean Code Part I: Code Chapter 2: Clean That Code! Chapter 3: First Principles Chapter 4: Meaningful Names Chapter 5: Comments Chapter 6: Formatting Chapter 7: Clean Functions Chapter 8: Function Heuristics Chapter 9: The Clean Method Chapter 10: One Thing Chapter 11: Be Polite Chapter 12: Objects and Data Structures Chapter 13: Clean Classes Chapter 14: Testing Disciplines
Chapter 15: Clean Tests Chapter 16: Acceptance Testing Chapter 17: AIs, LLMs, and God knows What Part II: Design Chapter 18: Simple Design Chapter 19: The SOLID Principles Chapter 20: Component Principles Chapter 21: Continuous Design Chapter 22: Concurrency Part III: Architecture Chapter 23: The Two Values of Software Chapter 24: Independence Chapter 25: Architectural Boundaries Chapter 26: Clean Boundaries Chapter 27: The Clean Architecture Part IV: Craftsmanship Chapter 28: Harm Chapter 29: No Defect in Behavior or Structure Chapter 30: Repeatable Proof Chapter 31: Small Cycles Chapter 32: Relentless Improvement Chapter 33: Maintain High Productivity Chapter 34: Work as a Team
Chapter 35: Estimate Honestly and Fairly Chapter 36: Respect for Fellow Programmers Chapter 37: Never Stop Learning Afterword Appendix Bibliography
Table of Contents Foreword Introduction A Note About Older Chapters The Structure of This Book Introduction (from Long Ago) Chapter 1. Clean Code There Will Be Code Bad Code The Art of Clean Code? Putting All This Together We Read More Than We Write The Boy Scout Rule Part I: Code Chapter 2. Clean That Code! The Cleaning Process Conclusion Postscript: Future Bob Playing with Grok3 Postscript Conclusion Chapter 3. First Principles Everything Small, Well Named, Organized, and Ordered
A More Significant Example A Final Thought Chapter 4. Meaningful Names Use Intention-Revealing Names Final Words Chapter 5. Comments Compensating for Failure Good Comments Bad Comments Conclusion Chapter 6. Formatting The Purpose of Formatting Vertical Formatting Team Rules Uncle Bob’s Formatting Rules Chapter 7. Clean Functions Small! Reading Code from Top to Bottom: The Stepdown Rule Switch Statements Clean Functions: A Deeper Look Conclusion Chapter 8. Function Heuristics Function Arguments Command Query Separation Prefer Exceptions to Returning Error Codes Structured Programming Conclusion
Chapter 9. The Clean Method Make It Right Example Conclusion Chapter 10. One Thing Extract Method Refactoring What Are Large Functions Anyway? Conclusion Chapter 11. Be Polite The Newspaper Metaphor The Stepdown Rule: Once Again The Abstraction Roller Coaster This Is How We Write, but Not How We Want to Read Chapter 12. Objects and Data Structures What Is an Object? Data Abstraction Data/Object Antisymmetry The Law of Demeter Data Transfer Objects The OO/Procedural Trade-off But What About Performance? Conclusion Chapter 13. Clean Classes Classes and Modules versus Files What Should a Class Contain? Chapter 14. Testing Disciplines Discipline 1: Test-Driven Development (TDD)
Discipline 2: Test && Commit || Revert (TCR) Discipline 3: Small Bundles Design Discipline Keeping Tests Clean Tests Enable the -ilities Chapter 15. Clean Tests Domain-Specific Testing Language F.I.R.S.T. Test Design Conclusion Chapter 16. Acceptance Testing The Acceptance Testing Discipline Conclusion Chapter 17. AIs, LLMs, and God Knows What Programming by Prompt Conclusion Part II: Design Chapter 18. Simple Design YAGNI Covered by Tests Maximize Expression Minimize Duplication Chapter 19. The SOLID Principles SRP: The Single Responsibility Principle OCP: The Open–Closed Principle LSP: The Liskov Substitution Principle
ISP: The Interface Segregation Principle DIP: The Dependency Inversion Principle Chapter 20. Component Principles Components A Brief History of Components Component Cohesion Component Coupling Conclusion Chapter 21. Continuous Design Continuous Change Continuous Design Sailing on the Four Cs of Continuous Design When Else Do We Design? Chapter 22. Concurrency Why Concurrency? Concurrency Defense Principles 2025 Update and Report from the Field Conclusion Part III: Architecture Chapter 23. The Two Values of Software Keeping Options Open Chapter 24. Independence Use Cases Operation Development Deployment Leaving Options Open
Chapter 25. Architectural Boundaries What Lines Do You Draw, and When? Plug-in Architecture Case Study: FitNesse Conclusion Chapter 26. Clean Boundaries Third-Party IoT Framework: Lots o’ Boundaries UI/Application Boundary Clean Boundaries Chapter 27. The Clean Architecture The Dependency Rule Entities Conclusion Part IV: Craftmanship Chapter 28. Harm No Harm to Society Harm to Function No Harm to Structure Soft Tests Chapter 29. No Defect in Behavior or Structure Making It Right Programmers Are Stakeholders Do Your Best Chapter 30. Repeatable Proof Dijkstra Structured Programming
Functional Decomposition Test-Driven Development et al. Chapter 31. Small Cycles The History of Source Code Control Continuous Integration Branches versus Toggles Continuous Deployment Continuous Build Chapter 32. Relentless Improvement Test Coverage Mutation Testing Semantic Stability Cleaning Creations Chapter 33. Maintain High Productivity Viscosity Managing Distractions Time Management Chapter 34. Work as a Team Collaborative Programming Open/Virtual Office Chapter 35. Estimate Honestly and Fairly Lies Honesty, Accuracy, Precision Lessons from Me Accuracy and Precision Aggregation Honesty
Pressure Chapter 36. Respect for Fellow Programmers Chapter 37. Never Stop Learning Afterword Appendix. The Clean Code Debate Introductions Method Length Method Length Summary Comments Comments Summary John’s Rewrite of PrimeGenerator A Tale of Two Programmers Bob’s Rewrite of PrimeGenerator2 Test-Driven Development TDD Summary Closing Remarks Bibliography
Foreword Micah Daniel Martin You hold in your hand the secrets for building high-quality software—secrets that will make you better than you are, secrets that will help you become a master craftsman. Like Antonio Stradivari (perhaps the best luthier ever), Uncle Bob has spent a lifetime curating and developing the best techniques for crafting code. Unlike Stradivari, who hoarded his secrets so that only he could craft the best violins, Uncle
Bob shares his secrets willingly, openly, hoping that you too will craft masterful code. This is the Way: the Way of Clean Code. These are my disciplines, my principles, my techniques. I strive to master them all. Why? Because they make me better. And, this is the way my father taught me. Yes, Uncle Bob is my father. He bestowed upon me the honor of writing this foreword. Furthermore, please allow me to introduce my brother, Justin, also a Clean Coder, who wrote the afterword. How appropriate that two second editions of Uncle Bob get to sandwich his second edition of Clean Code. (Yeah . . . that sounded cheesy as I wrote it, but I’m going with it.) Let me tell you a little about Uncle Bob, or at least the version of him that I know as “Dad.” One of my earliest memories is riding on my dad’s shoulders, playing Robot. The rules are simple. My dad was the robot, and he did whatever I told him to do . . . to a T. Me: “Go to my room.” Dad: “I don’t know how to do that.” Me: Thinking . . . “Turn.” Dad: “Which way?” Me: “Turn right.” Dad: Starts turning clockwise. 90°. . . 180°. . . 360°. . . He doesn’t stop turning. Me: “STOP!” Dad: Stops. Stands still, facing the absolute wrong direction. Me: “Turn right . . . STOP!”
Dad: Turns and stops obediently. We are now facing down the hallway, the right direction. Me: “Start walking.” Dad: “I don’t know how to walk.” For the next few minutes, I teach the robot how to “walk” by lifting a leg the appropriate amount and falling forward, then repeating with the other leg. We agree to name this activity “walking.” Me: “Start walking.” Dad: Starts walking. Me: Feeling exhausted by this ignorant robot, but also victorious that I successfully made it do my bidding, I prepare for the final maneuver, a left turn at the end of the hall. “Turn left!” Dad: “I am still walking” . . . and CRASH we go into the wall. Apparently the robot was single threaded. We bounce off the wall and the robot continues to walk . . . CRASH we go into the wall again . . . and again. Me: Laughing uncontrollably. At that tender age of 4 or 5 years old, my dad was teaching me how to program with the Robot game. It was fun. Fast- forward 5 years, and my dad brings home a Commodore 64. “What is it?” I inquired. “A computer,” my dad responded. “What is it for?” I asked, still confused. “Well, with a computer you can blah blah blah blah, blah blah, you can even play games.” “Games? Show me!” I adopted that Commodore 64, or maybe my dad gave it to me . . . regardless, it lived in my room and I played lots of games on it. There was a kid in my neighborhood who knew how to pirate games, and we’d do
a weekly floppy disk exchange. Other than loading games from disks, I didn’t really know how to use the computer, and anytime something went wrong, like “PRESS PLAY ON TAPE” . . . I’d shout “DAD! HELP!” At one point, he sat me down at the Commodore and introduced me to Logo, a programming language with turtle graphics. He showed me how to make the turtle turn, move forward. It was the Robot game! I played with Logo for a while and it was . . . boring. Back to gaming. Then, I observed my dad working with Logo for what seemed like forever but was probably just a couple days. When he was finally done monopolizing my computer, he showed me his Lunar Lander game that he’d just built. It was a jaw-dropping moment as I realized this is how games are built. Wow! Lunar Lander was inducted into my game rotation, and I proudly showed it off to my friends. A couple of years later, my dad brought home a brand-new Apple Macintosh. It was AMAZING. “What’s that thing?” “This is a mouse.” So novel. And it had more games. Better games! The Mac lived in my dad’s office (basement), but when he was at work, the Mac was mine. Similar to the Lunar Lander incident, my dad spent weeks monopolizing the Mac to create a game he called “Pharaoh.” Pharaoh was much bigger than Lunar Lander. You were the pharaoh, and your goal was to buy enough oxen, plant enough crops, and sustain enough workers every year to build a pyramid before you died. It was a fun game, and I could tell my dad had fun building it. Programming is so much fun! That’s the conclusion I had when I reached college age. For my whole childhood, if I wasn’t having fun playing on the computers, my dad was having fun programming them. Why would I choose any other major than computer science? Programming in college
was . . . not fun. Upon graduating, I was offered a job at ThoughtWorks, and, thank goodness, my dad offered me a job working with him at Object Mentor. Of course I accepted my dad’s offer, where I got to work with some of the biggest names and best software guys in the industry. Once again, programming was fun. It was at Object Mentor where I learned the way of Clean Code from my dad, building lots of internal tools and open source projects like FitNesse, that you’ll see later in this book. Object Mentor was primarily a training and consulting business. We told people how to build good software. We didn’t really write the software for them. I’ll admit that after several years as a trainer, I got an itch to build software again, instead of teaching how to build software. An opportunity arose, and Object Mentor started developing software for a client. It was great, and it turned out to be a solid business model. So, I convinced my dad that Object Mentor should do more software development contracts. He agreed. And then I tried to convince him that I should run that branch of the business. Oops . . . that was one step too far. His response hit me like a truck. “If you want to run things, you should start your own business.” Wow! Was that his way of putting me in my place? Or was he actually suggesting I start my own business? I concluded it was the latter, so I told him, “I quit.” I created a company called 8th Light. It was (and still is) a contract software development company. Clients hired us to build software for them. What was unique about 8th Light was that we practiced the Way of Clean Code. We didn’t call it that, because the first edition of Clean Code hadn’t been written yet. But we put into practice everything that my dad had taught me. The Uncle Bob Way of Coding doesn’t have the same ring. Moreover, 8th Light adopted apprenticeship, which is something we had dabbled with at Object Mentor.
Comments 0
Loading comments...
Reply to Comment
Edit Comment