76. Clean Code | Robert C. Martin (Uncle Bob)


Clean Code

Robert C. Martin (Uncle Bob) is the co-founder of cleancoders.com, author of several very popular books including clean code, public speaker, idol of many programmers.

Uncle Bob joins to talk about clean code, such as its definition, guiding principles, best practices, test coverage, TDD, etc.


Sponsor

Proton Text is a complete SMS texting solution built for the Lightning Platform, and by one of our previous guests Pat McClellan.


Go to getclayton.com/salesforceway or use the code SALESFORCEWAY to get one month free. The offer expires on October, 31st 2020.


Links


Video

Video format of this episode on YouTube


Video Teaser

The YouTube Video URL


Contact Me

If you enjoy this podcast, please reach me out to let me know your thoughts or simply say Hello. My (Xi’s) contact info:

Take care, until next time :)!

Transcript

AI-generated, unedited.

[00:00] Our sponsor today is Proton Text, a complete SMS texting solution built for the Lightning platform by one of our previous guests, Pat McLehlan. Here is reason number three that admins and users love this app. It comes with the Proton Blaster. It's true, Pat built a Proton Blaster. It's a Lightning Web Component that lets users plan and schedule SMS blasts to campaign members or to a blast list created from any list view or CSV file. Whether you're blasting to a hundred students or volunteers or to fifty thousand leads, setting up a blast is as easy as creating a calendar appointment. It's not magic, just good design. Check out the downloadable processes and flows in the automation library at protontext.com.

[01:12] Hey everybody, this is Xi Xiao. This is yet a new episode of Salesforce Way podcast. Today I'm sitting with. A really, really, really, really wonderful guest with me, Uncle Bob Robert C. Martin. Hello, Robert. Hello. How are you? I'm good. I'm good. You know, at the very beginning of this podcast, I had the chance to talk with another Robert in our Salesforce ecosystem. We talked about clean code, and at the time, we said, "Okay, you are Robert, but you're not the author of the clean code book." But now today, I had the chance to really, really to talk to you again. I'm so excited. You know. Well, thank you very much. It's kind of you. Yeah, just a little introduction for the minority of people who don't know you yet. So you are the co-founder of Cleancoders.com. And you are the author of several really, really famous programming books, including the Clean Code book. And also, you are a public speaker. You go all around the world to talk about the things that you're passionate about. And you are also like the idol of many programmers, myself included. Yes, you are. So, so Uncle Bob. So today, I want to bring you here to talk about the clean code, which has definitely changed. The way of thinking about the programming, the way of doing programming for many, you

[02:42] know, programmers around the world. So, do you remember when the book was first published? Which year? Oh, let's see. It's a challenge to you, maybe two thousand something or other. Um. Yeah, it's two thousand eight. It doesn't really matter. Yeah. I've got a copy of it here. Let's see. All right. Yeah. You know. So I can give you the copyright date.

[03:08] Um, two thousand and eight. Yes, that's already publication date. Yes, yes, that looks like the copyright date, two thousand eight. Yeah, okay, yeah, yeah, indeed. I'm curious before two thousand eight because my programming career started in early two thousand. So there's like still a gap for me before two thousand eight. Was it a thing? The clean code was it a thing? You know, in the industry, was people really talking about it? People were talking about writing code well. You could you could get hints of that from books that had appeared before. Kent Beck wrote a book called Implementation Patterns. Prior to that, he had he had written a book called Small Talk Best Practice Patterns. And those were books that were focused on, on writing code well from a. Um, a patterns point of view, almost a mechanistic point of view. He would he would describe certain coding. Practices certain coding snippets, and discuss why they were good ideas, but there was no. There was no authoritative work on what good

[04:38] clean code was, and and that was because most of us did not feel like we had a right to publish a book like this. It had been on my mind for some time, but but it takes a a very large degree of arrogance. To write a book that says this is clean code, and and so for a long time I resisted the idea, and then at some point I thought, well. Somebody's got to write this book, and I I presented it in the book as. You know my standards. They don't have to be your standards, but they are my standards. This is what I do, and I I had enough experience. I felt at the time to be pretty authoritative about it, and so I I bit the bullet and I wrote the book. I got a lot of people to help me with it too. How long did it take you to? Books take me about three years to write. Some some are a little faster, some are a little slower. But in general, if I start a book project, it's going to be three years before I'm done with it. And that's because I will write for a week, and then I will stop writing for two, and then I'll write for another week, and stop writing for three. It's a very stochastic process. And and of course you know real life interferes a great

[06:08] deal. So I would have to travel around the world, and I can't really write much when I'm traveling around the world. And then I would get a spare week or two at home, and I would write a book. I've got a new book on my screen right now. I'm trying to write a little bit into it, but it's very it's it's hard to find the time. So it takes a few years. So it was it the first book you written? Oh heavens no!

[06:36] Oh heavens no! Let's see, let's see, let I'll get you the first book I ever wrote. It's very embarrassing. Um, where is it? Where is it? I know I've got it up here somewhere. The title of the book here it is. Yes. Okay. This is a one thousand, nine hundred and ninety what five book? Yeah, one thousand, nine hundred and ninety five. Designing object oriented C plus plus applications using the Booch method. This is before I realized that short titles are better than long titles. The book is loaded full of all kinds of you know Booch diagrams and lots of designing techniques and it was primarily about object oriented design in C plus plus. It sold tolerably well in the nineties, but that was my very first. Okay, it definitely it was the first book that I start to know you. So if we start to talk about the clean code book and concept, did you have your own definition of clean code? Did you write it in your book? Because I know that you talked with different. Famous programmers, and you put what's their definition. I don't know. Did you already come up with your definition as well? I had my own vision of what I thought should be clean code. And so that's the first part of the book is just you know my understanding of what it takes for code to be well structured and clean.

[08:06] But again, there was this problem of arrogance, right? If it was really common. In the even ten years ago, to not try to assert yourself as an authority, and so I got several other people that I I know and trust and and like a great deal, to put their own ideas in, so that the book would be a spectrum of ideas, not just you know my narrow view. Do you have your favorite quotes from those programmers in your book? Well, anyone is your favorite quotes? Favorite quotes from the other programmers. So, let's see, because at least I love one of the the definitions that Michael Feathers put there. It's like a. I don't know if you like that one. Oh yes, well, it's one of my favorite descriptions of, of what clean code is. Clean code always looks like it was written by someone who cares. That's a good one, and that that's that's Michael Feathers' moralistic a definition of clean code, and and it's a good one because many programmers look at code and realize that the author didn't care about them at all. They only cared about getting that

[09:37] code written and working, and not about anybody else. And Feathers' Feathers' idea is no, when you read code and you get the feeling that the author of that code cares about you, well, then that's clean. That's good clean code. My other favorite quote from that particular part of the book was Ward Cunningham. Ward Cunningham said, "Let's see if I can pull this out of my memory. Clean code."

[10:12] You know you are reading clean code when each routine you read.

[10:22] Is pretty much what you expected. That's how it goes. You know, you are reading clean code when each routine you read is pretty much what you expected. And that was one that took me a long time to get my head around because when I first read it, I kind of shrugged my shoulders and said, "Well, Ward, you know, whatever." And then I thought about that for a long time, and and realized that I had almost never read code. That was pretty much what I expected. Yeah, usually I'm reading code and going, "Oh my God, what the hell does this code do?" And Ward is saying, "No, no, you you read the code and you agree with it." And the information from the code flows into your mind with no impedance. It's it's pretty much what you expected, and that that is good clean code. Of course, I would expect something profound from Ward Cunningham. You know, Ward Cunningham is the guy who invented wikis and worked with Kent Beck on Extreme Programming. He's been, you know, this guy in the background for years that almost nobody knows, but he's been remarkably influential. I see. For many of the young programmers, how do we really know the code is clean? You know, back in the university time for me, is that I thought a programmer,

[11:53] the definitely the task for a programmer is to get the job done to make the application work. While I don't really care about the reader, if the reader doesn't understand, that's them. That's they are not smart enough. That was naively in the early days what I thought. But in your book, you talked about what is the clean code? What are the definitions of a clean code? What are you know those principles of a clean code? Could you give us some good examples? Well, there's a number of lower level principles. The the overriding principle is this: you are not done when it works. Getting the code to work is the easy part. Getting the code to read well is the hard part, and the reason you're really hired. It doesn't take an awful lot of skill to cobble together of a a program that works. You know, you you learn to do that in the first couple of years, and and after you know, after a while, you can do that. It takes a fair bit of experience and effort to then massage that code into a a state where other people can easily pick it up. Now, some of the mechanics that I talk about in the book are obvious things like you know choosing good names. You know, think about the names. You don't just kind of throw a name out there and then let it stand. But think about names.

[13:23] Keep your functions very small, and and by very small I mean very very small. Extract functions as much as you can and give them good names. And simple simple things like that will go a very long way to helping you. Organize the code in such a way that other people will find it to be pretty much what they expected.

[13:56] I see, but good namings are difficult. I'm not an English native, to sometimes I'm really scratching my head to think about what name should I put for you know for this variable to make it easy to understand. I don't know, is it better, easier task for natives? Oh, I don't know. Um, obviously, if you're if you're programming in English and you're a native English speaker, it's probably a little easier. On the other hand. A name—it's—it's very hard, even for a native English speaker. It's very hard to choose the right name, and it's hard because we often don't know what. The function we're writing is actually going to do. We we think we have an idea, but then we write the function, and it turns out to do something different and something more nuanced. And the name isn't right now, but the name is there, and so we let it stand. And it would be better to go back and think about that name, and and maybe the maybe that will affect the name of the class that you're in, and maybe that will affect the name of the, of the namespace that you're in. The effort of choosing names is one of the most fundamental design efforts. That you can engage in, and very often it is that effort of choosing the right names that

[15:26] will profoundly impact the shape of the overall program. There, there comes these moments of a vast insight when you're staring at this code and and it just doesn't look right and it doesn't feel right and you suddenly realize oh that thing is not that it's this other thing and that changes the shape of a thousand lines of code around it. And and those are wonderful moments. Of course, there's a little bit of effort that's required after that. But this wonderful moment, because then all of a sudden you can put this code into a shape that makes perfect sense to you, and it's going to make perfect sense to everyone else. And it looked like it was written by someone who cares. Hmm. But I wonder, does it make sense for the managers or other people in the team? Because you've get the job done; it is working. But then you still need to spend the extra time to them. Maybe doesn't make sense. But to yourself, you understand it's important. Yes, but how how do I justify the the extra time I spend on that? Yes, well, I mean, t here is t here is about eight different things I could say about that. First thing is how many times. Have you looked at code on your screen and been significantly slowed down by it? Either because somebody else wrote it and you couldn't understand it, or you wrote it a week ago and you can't understand it. Right, and that slows you down. Now, here's the problem with that:

[16:57] that code will slow you down every time you look at it, and every time anybody else looks at it. There's a huge magnification effect. Bad code slows everybody down. Good code slows nobody down. Bad code slows everybody down. So you, as the programmer, are making this false trade-off. You believe that you are going to save time by getting it working and walking away, and not spending a little extra time cleaning it up. The effect of that, of course, is that you then slow down everybody else on the team forever. And the magnification effect is huge. And what happens to teams, and you've probably experienced this, is that they will start out relatively fast because there's very little code in the system. And then, as time goes on, the entire team slows down. All the estimates start to grow. Everybody gets paranoid of touching the code. Every time they touch the code, it breaks in a dozen different places. They have no idea why. They know they're going to be spending massive amounts of time debugging and struggling with this growing mass of unruly code, and everything slows down. And the managers notice that. Of course, the managers are all going. Well, what the hell happened? You guys used to be fast. Now you're slow. You guys have changed. You guys have gotten lazy. You guys have become bad programmers,

[18:28] and that puts pressure on the programmers to go even faster and make even bigger messes. And the whole thing just goes out of out of control. Hey friends! This episode sponsored by Clayton. Clayton is the first developer-friendly code review bot that helps Salesforce teams catch security and design flaws before they become problems. It's up and running in Clux and works with GitHub, Bitbucket, GitLab, and Azure DevOps. Go to getclayton.com/salesforceway to get one month free.

[19:03] It's getclayton.com/salesforceway. You can also find the link in our show notes. Thank you for supporting our sponsors.

[19:14] So that's number one, right? If you take the time, a little bit of time, to clean up the code that you just wrote and got working, you will save massive amounts of time. Tomorrow, and the day after, and the day after, right? So that's one. But there's another factor here, a much larger factor. You used the term "How do I justify?" and I answer that. Why do you have to justify it at all? Why is it anybody else's business? You are the expert. You are the one who knows how to write code. The manager does not. The manager does not know how to trade off good code against bad code. The manager doesn't know what good and bad code is. It's none of the manager's business. That's the reason you were hired. You are the expert. You know how best to serve the company you are employed by, and therefore you should not ask. A manager, if it's okay to clean up the code, that's a that is the wrong question to ask. First of all, it's an unfair question to ask because the manager has no idea what that means. Secondly, it's a cowardly question to ask. Because you are asking the manager to take on the risk that you have decided you

[20:44] do not want to take on for yourself, but you know you should, and so it is an unethical question to ask. It's a cowardly question to ask, and it's just the wrong question to ask. You know how to be professional. Be professional. Okay. Yeah, I I get the point. I get the point. It takes some time to digest, especially the first time when I hear about this. Uh huh. But does it mean each time when I touch the code, I should spend a certain amount of time to just massage the code a bit? Oh, very often. That's a great idea. A large chunk of time. Yeah, no, that's very often a great idea. You bring code up on your screen. And you kind of look at it sideways and think, well, you know, I don't really understand it. Maybe I could fiddle with it. Maybe that's functions too big. I'll split it in half. Change this name. You know, things like that. And and once you get it into a position you really understand it well, then you can modify it. It's much easier to modify code that you understand. Now, all of this implies something. If you are going to fiddle with the code, you need some way to keep that code safe because fiddling with the code can break it, and you don't want to be the one who breaks the code. So you need something that keeps that code safe, and what keeps that code safe

[22:14] is a suite of tests, a suite of tests that you have written through through significant amounts of discipline, and you can push a button on your screen, and those tests will execute within seconds. And tell you that you haven't broken anything, and if you have that, if you have that suite of tests, well then you can make any change you want to the code because you're not going to break it. Or if you do break it, you're going to find out instantly and put it back the way it was. This is one of the big problems. If you want clean code, nobody writes clean code. Everybody makes a mess because it's hard enough to get the code to work. Then you want to make it right. After you make it work, then you want to make it right. But if you don't have tests, you can't make it right because you're afraid. You're afraid you'll break it again. And so the only way to have clean code is to have a suite of tests that you trust with your life. And you have to start those tests right away. You've got to be writing those tests all the time. Have really high test coverage. You know, as close to one hundred percent as you can get it. So that when you push that button and you see it go green, you believe that the system works the way it's supposed to. Let me ask you two questions. This is more or less Salesforce related. So when we deploy code into Salesforce production

[23:44] environment, there is a rule that your test must cover seventy five percent, really or over. Yes. Otherwise, it will fail you. Okay. So it's okay then if twenty five percent of the code doesn't work. It's not about the working; it's just about the code coverage, right? Well, yes, okay.

[24:09] We only have to cover seventy five percent because the other twenty five percent is certainly going to work.

[24:17] So I have a problem with numbers like that, right? Numbers like that are completely artificial, and they're always wrong because the only number that makes sense is a hundred percent. Now you will never get to a hundred percent, or or it's very hard to get to a hundred percent. It's it's an asymptotic goal. It's one of these goals that you are always pushing upon, right? You need to always make it a little better and a little better. So seventy five percent is a a false goal, and it has. An extremely bad result, and the bad result is this: if you are going to fail the build. Because you've you did not get to seventy five percent coverage, then the programmers, in order to get the build to succeed, will remove assertions from the tests, and get the test coverage high. You know it so well. You know it so well. Well, of course, you know I've been programming for fifty years, but but. When when manage see the code coverage is a metric that managers should never look at and should not know anything about because they don't understand what it means. It does not mean that you have covered seventy five percent of the code with tests. It means that you have executed seventy five percent of the code with or without any assertions. And that's a meaningless

[25:47] number. When the pressure is high, programmers will always make the decision to remove a few asserts, get the number high. We'll go back and fix it later. Don't worry, the pressure's on us. Oh, oh, and then of course you never go back and fix it later. Managers should never touch that metric. It's a it is a very technical metric that programmers can understand and programmers can use privately to understand the the level of of coverage of their tests. And then this artificial limit of seventy five is completely bogus. I see. I see. But how how can I get the test? In the good shape. I mean, I have seen projects that we really are in the time pressure. We need to get it to deploy to production. Is there a good principle to guide us? You know, we have a good test that is surrounding our production code, so that we are safe. There are a number of good practices here. Now, the first one is that test code is not. It's not an under citizen. It is not lower class code. Test code is as important as production code, and all the same rules apply. You keep that test code clean. You design it well. And by design, it well,

[27:17] I mean you manage the coupling and cohesion of the test code. The test code is part of the system and must be designed to the same standards as the system itself. Like what you just mentioned, the good naming, small functions, those apply to test as well. Yes, all of those decoupling and cohesion and making sure that you're not you know breaking a thousand tests when you touch one bit of the production code, all of those are standard design techniques that you would use in any system without tests. And you would also use them with any in any system with tests. The other the other discipline that is extremely helpful is to make the writing of the tests such a high priority that you write them first. You write them before you write the code you are testing. You write a test, and then you write the code that makes it pass, and then you write the next test, and you write the code that makes that test pass, and that's a it's a discipline called test driven development. I'm sure you know a fair bit about it. There's much more I could say about it, but following that discipline will guarantee you a suite of tests with very high coverage that. You are never playing catch up with. You're never trying to catch up by adding a bunch of tests.

[28:48] You have the tests first. Hmm. But this TDD practice model does not guarantee your code is co. Your test code is cohesive. It's flexible. When you touch a production code, it won't break. It's just a guiding principle, right? There are the extra stuff you still need to learn when you write code. Many, many things you have to learn about how to properly write tests, how to properly decouple tests, how to properly design tests. There's many, many things to learn about that. Test driven development is one of those disciplines that requires many months of of experience and practice to do well. It's not one of those things that you can read about and then the next day you're doing it, or at least you're not doing it well. But does it mean when I do TDD, the test code, the line of test code is more than the production code? Is that always, almost always the case? What do you mean by more? Let's say if my production functionality has two thousand line of code, then my test code could have been ten thousand. Is that typical? Well. My own experience is that you get close to one to one thousand lines of code and a thousand lines of tests. Sometimes a little less than that. Sometimes it's a little more. It depends on the complexity of the production code.

[30:18] It is. It is never. I've never seen it go two to one. You know, twice as many lines of code in tests as in production. Really? No, I've never seen that. Usually it's it's close to one to one, or maybe three quarters to one, or something like that. And the reason behind that is that the tests themselves, if they are well written, remain very small. There are a lot of them, but they're all very small. The production code grows in a completely different way. The production code grows in this way that promotes generalism and partitioning of functionality. So you get this family of modules and classes on the production code side, and you get this linear list of really tiny tests on the test code side. And okay, maybe it it gets close to one to one. Okay, I see. That's definitely the one of things it's puzzling for me because when I write the test first, I'm still start to practice TDD. Is that when I see the production code? If I understand the business requirement for a feature, then my test need to I need to create maybe six or seven test. Small tests to test the different path of the the the code, yeah, and the need tends to get longer than production code. Maybe it's just my practice that doesn't, you know,

[31:48] go well. You will you will see that. In in very early tests. So as as you're writing, you've got brand new code, right? And you're writing some tests, and you're adding code, and writing tests, and adding code. And yes, the tests will grow larger than the code at first. But then you'll look at this code over here and think, Ah, man, I gotta, I gotta split that up. I gotta do something with it because it's gotten messy, and you'll start to pull it apart into little chunks. And those little chunks will begin to grow, and they will begin to accumulate functionality. But your tests will still go through the original classes, the original modules, and access the access the business rules through those original modules. While this stuff out here continues to grow, and the the ratio of tests to production code begins to shift. So early on, you will see that you know more test code than production code. But that's in the first thousand lines. By the time you get like to four thousand lines, the the the shift is gone the other way. Usually, usually that's interesting. Okay, I see. I see. So, if we talk about clean code, there are code static tools to analyze the code. For those tools, do you think it's important, or does it help much for us to write cleaning code? Oh yeah, static analysis tools are wonderful things. They can give you hints. For example, just a a simple count of the number

[33:19] of lines in a function. That's a really good. That's a really good metric to have if you've got. If you do the the average and you find that the average function is five lines, that's pretty good. Yeah. Okay. And then you could find the the few. Yeah, five. That's a pretty big function, right? As long as they're like five lines long. Okay, that's good. If you get and you find that there's you know a dozen functions that have ten or fifteen lines, well then that tells you you should go look at those. And you know, a good tool will just give you a list. You know, these these ten here are a little bit larger than the mean. You should look at those. Another good good static analysis would be cyclomatic complexity, which is just usually just kind of a count of the number of indentations. It's almost like that, and that's a that's a useful that's a useful metric. One of the most interesting metrics. That I've run across is a combination between a static analysis, cyclomatic complexity, and a dynamic analysis, code coverage. And and this one is it's it's called the C R A P metric, the crap metric, and it's a relationship between cyclomatic complexity and coverage. A module that has a high cyclomatic complexity and low coverage. Is a pretty dangerous

[34:49] module, right? Because it's not covered enough and it's complicated. Now, if it's got low cyclomatic complexity and low coverage, well, that's probably not a big deal, right? Because there's no complexity there, so you maybe you didn't even bother to test it. We do not, for example, test our getters and our setters. Right? There's no there's no reason to test those, and so they would be low cyclomatic complexity and low coverage. Right. That that makes sense. It's a real interesting metric, and you can look it up, and and see. There used to be tools to calculate it. I don't know if those tools are around anymore. Okay, so in your Clean Code book, the first part, first half of the book is about those principles, ideas. What are the Clean Codes? How to define, you know, how to make the intangible things become tangible for most of the programmers, and the second part is you use a example, a Java example to really go through your thought process from a messy large classes and then refactor it into small. I found that the second part is really difficult to follow. Not because you did a bad job. It's just you know it's in the book. There's so many line of code. Maybe if it's in a video format, it's better. That's just my personal idea. So it it gave me the hint that it's really hard to write clean code.

[36:20] Not just learning those principles. There are so many. I mean, learning the principles is good, and it to bring you really far. But still, if you want to be a great programmer, really know how to do all this stuff easily. That's like a thousands or even ten thousands of hours of practicing for the further languages.

[36:44] Hi, this conversation continues on the next episode. See you next week.

3 Comments

  1. hojjat 2020-09-24
  2. Sérgio Ferreira 2020-09-29
    • Xi Xiao 2020-10-04

Leave a Reply