 I won't be offended at all so what I'm going to do here today is to go back far down to the basics We know about several refactoring techniques. We know about Extracting methods. We know about extracting fields. You probably have read of Martin Fowler's book. If not, you should definitely read it We know these kind of techniques But what I want to get to is something even more fundamental than you know, even before applying some of those Why should we refactor? How do we approach refactoring? What are some of the techniques we could use to make refactoring a more productive, you know task So that's what I'm going to focus on and what I won't talk about here is a laundry list of refactoring techniques You know the reason is twofold one. I can never remember those lists No matter how hard I try the best way to really get good at those is to do them and Second you can find them in most of the books. So why should I waste your time talking about what you can find in a book? So I'm going to share more about, you know, what's worked for me and how things have evolved What I would like for you to do is to ask questions make comments, you know something that may have worked for you I want to know about you. I want to learn from you or ask questions about. Hey, that kind of doesn't work This is the problem I ran into absolutely any time is a great time to you know ask questions make comments Sounds good All right, let's get started So what is refactoring? Refactoring is your genuine desire. I'm going to say genuine because why else would you do it, right? It's a code that works and you're going to spend your time fixing the code that works And the only reason you would do that is because you're genuinely interested in improving it There's no other reason to do it to improve the quality of your code and the design in it Now of course you say hey, we believe in developing working software Actually, I would like to develop working relevant software But then why do I care about quality of code after all the customer never sees the code, right? In fact, you hope the customer never sees the code. So why bother wasting time on code quality? That's a total waste of time, right? Well, I'll tell you why it's extremely important to care about quality of code Because it's very simple, right? You cannot be agile if your code sucks As simple as that your company says you're all agile, right? So you go to the customer. So here's my customer I say customer don't worry. We're agile. The customer is all hyped up excited. Really. What does that mean? You tell us what you want to change and we will do that for you real quick and The customer begins to tell you what he wants as the customer is telling you that in the back of your mind You realize oh my god, that means I got to touch that code The one that you touched last time and could not go home that weekend Now you're gonna convince the customer. That's not a good idea, right? So you cannot possibly be agile if your code sucks So if you really want to be responding to change quickly The only way that's going to happen is if the code is a good quality Otherwise we can might also forget about it. I'm not saying that's the only thing that's needed But that's one of the essential things and without it. It's almost impossible to achieve that Or you say wait a minute, but it takes time Developing high quality code takes a lot of time. Well, I'll tell you it takes incredibly a lot of time But it's more complex than that Who here can write wonderful code or is your hand if you can? Two people you're all lying. I'll tell you I write code that sucks You don't want to look at the code. I write you're gonna say really? This is your code, but you know what I'm really good at. I'm extremely good at finding fault with your code So I found out this dichotomy, right that I really suck at writing code But on the other hand, I'm so good at finding fault with other people's code So I realized why should I waste time writing great code when I can write some crappy code real quick I can give it to him and while he tells me how my code sucks I can look at his code and say how his code sucks in the end of the day. We all have good code So don't pretend that you can write good code because nobody can write good code But we all collectively can and that is why we also need to refactor it So it takes time to do it But why should we really care about it because lowering quality Lengthens the development time if you really really say, you know what my project is going too fast What do I do write shabby code that'll take care of your progress, right? So one of the best ways to mess up a project is to really write poor quality code That's one of the first laws of programming. We need to be careful with So why should we refactor? Well, the first reason is to make the code easier to understand Because we cannot obviously maintain code that we cannot understand. So that's very important to do that It's easier to maintain. In fact, we want to do more maintenance You know, we think that maintenance is a bad word, but it really is not Robert Glass has a book on fallacies of software development and one of the things he says in it is That a good software goes through more maintenance If you're a mechanic shop, you want to do more car maintenance every day because that's what your profit is If you're developing software, you want to make more releases with more features more quickly And that is what maintenance is because we are so bad at doing it We kind of give a negative connotation to it But we want to be able to do more maintenance and to be able to make effect of the changes We want to make and that's very important But why should we care about all of this and the reason is the only constant is changed, right? We always have to be prepared for change and and that's basically what your actlet has said is the only constant is change So we want to be able to embrace this change now of course, there's a more important reason because as this beautiful saying here says programs must be written for people to read and only Identity for machines to execute we read code more than we write But you ask yourselves Why is it that we most of us write bad code and the reason most of us write bad code is Most of us have read bad code. I mean, this is sad most of us even don't know how a good code looks Because we've seen them so much we don't even realize it And so if you find a good code make a big deal about it immediately tell the word Oh, look how beautiful things look how beautiful this code is and why it is good So we can all kind of you know relate to that and pick it up more. That's very important So one of the reasons to do this is because you cannot write perfect code in one sitting It is impossible if you think you can't write code in one sitting correctly That just means that you're in an illusion Nobody can and it takes an iterative approach You write something and then you evolve it and refactor it and to me I really started appreciating writing code more after I wrote a book because when I wrote code nobody ever saw it In fact, you take kind of take pride. It's my code right when you write books You cannot do that assuming you want to you know really sell the book and the editor reads the book And he pokes your eyes and says do you know how to write English and then he corrects you and then you give it to Tech review the guys who do tech review don't pat you in the back and say great job They say do you know how you suck and then they tell you how you should improve it and by the time I have copies of my first version of the books and I look at what comes out and it's like wow It's it's did I do that right and it goes through so many divisions and when I did that I realized my God if only people to read my code the way they read my book Meaning as it is being evolved how good the quality of my code would be and that's one of the things I started doing is to make sure the code gets reviewed and and gets better And it's a way for us to learn because we cannot create a perfect code in the beginning It's impossible and designed rather than happening just once right at the first it has to evolve Continuously during the development process nobody can design it once and say I'm done and if somebody tells you I Designed this product. It was so cool and we never changed the design What you're telling you is their project got cancelled Right because any product that is useful has to evolve and as a result its design has to evolve as well So you have to accommodate the design. That's very very critical and without it. It's impossible to achieve it and code That's hard to understand is worse than the code that is lost You know if the code is lost you can tell your boss. We don't know where the code is seriously We looked for it hard and fast. We couldn't find it all that we have is this binary and What does the boss say? Okay fine go write it and you can rewrite it But if the code is in front of you, they won't let you rewrite it and you sold you to your way and you're scratching your head I work for a company. We did simulators, right? These were million-dollar simulators We were selling and when we looked at the simulator one of the most important thing in the simulator at the very core of It is a timing engine because this is the heartbeat pulse of this and the guys who wrote the code We're no longer with the company and it came down to we have to maintain it So I took one myself and said I'm gonna understand this code I started reading it and about three weeks later. I was like yep. I understood it Well, okay, what do we do now that know that you understand it? I said I'll write a document about So I described how it works And about six months went by a programmer who's much better than me came on on board He knows the domain very well knows everything more. He read my description read the code and he said you are totally wrong That's not the way the code works. I Said wow, so how does it work and he said I don't know We kind of gave up and this is when I love managers because managers have the best metaphors And my boss said we'll pour concrete over it. I'm like wow, that's so awesome Right, and so we started putting concrete over code meaning don't touch it, right? And you fear this code like this dark room in the grandma's house, right? They tell you whatever you do don't go into that room because anybody who went there never came back And now you don't want to touch this code so go home don't touch that code, right? That's not the way software should be maintained, right? So that is more important to be able to maintain it So we have to be able to evolve it So one of the mantras that I follow is make it work make it better Don't pretend that you can write good code in the beginning make it work first make sure this is exactly what you Wanted to be then make it evolve and when I say make it better Not make it better in seven months make make it better in two weeks Right away before the end of the day a small piece of code that works think about this for a minute Frederick Brooks said go ahead and build a software and when you're done with it throw it away and Then try again and you have a chance of getting it Now tries telling that to your boss at work on Monday Boss I went to the session and they reminded me of Frederick Brooks. We got to create this software and we are done We'll throw it away That's the easiest way to get fired from work, right? And the boss says no no no no we got to release the software, right? But does it mean that Frederick Brooke is wrong? Not at all the man is actually sage wise. He is correct But how could we follow his advice of throwing software well? I realized the man is right, but I just misinterpreted what he said Imagine you don't wait until the end of the software to throw it, but you throw everything you do every few minutes Look at how easy and trivial it is now you write a little code and say well that sucks and You immediately refactor it throw it away start over and so you take these small steps and don't tell your boss You threw away code you wrote in the past five minutes You can still keep your job right fantastic code and build a software and learn from it And this is exactly where agile development fits in because rather than trying to build this massive product And then realize we did it wrong Why don't we do a thin slice of fit learn from that experience get the feedback throw it away evolve it makes a lot of sense Isn't it so what he said makes a lot of sense when we approach it in smaller qualities quantities like that? So refactoring reduces the risk In developing software it can provide us a fairly lightweight pragmatic design Unfortunately, this is not guaranteed It takes a certain amount of effort on our part to be able to achieve this. That's very important So what is refactoring after all? It's an art of improving the design of existing code beautiful word. Look at that It's the art. It is not engineering. It is where you sit there and say in fact I'll tell you this is what really caught my attention. I Became a programmer because of the science in programming. I Remained a programmer because of the art in programming That is where the fund really is if it was purely science would have moved on to God for a bit of manager some other place, right? But I'm still a programmer today because of the art in programming that is where you write the code and you can see it evolve And you can just look at abstract and say hey This is how it's going to evolve and you can just sit there and tweak it It's so much fun to see that happen There's such a process of changing a software system in such a way that it does not alter the external behavior of the code Yet improves the internal structure. Now think about this for a minute. It doesn't do anything different yet You are changing it. This is what gets you in trouble with the boss The boss says wait a minute when you're done with it. It's not going to do anything more for me Why should I pay you to do it? So you have I don't like the other day. I was watching one guy He was complaining endlessly until he paged up and found that he actually wrote it doesn't remember anymore He doesn't complain anymore. It's like, okay, that doesn't look that bad anymore, right? So we all have this tendency to dislike other people's code or code that we think it's not ours So just because you think it's got to be refactored doesn't mean it's got to be refactored Consider the cost of change and the impact of change how much is going to cost to change it? What's the cost of changing this? Get a second opinion Just because you think this is a great change to make You can come over here and join us. That's okay. Yeah He's probably gone through some code himself. Okay, so get a second opinion, right? Hey, I'm you know thinking of this particular change. What do you think? The person may say well, that's a great idea. Let's do it Or the person may say have you considered these other situations and you end up really realizing There's something else that need to be done, right? There's no fun. Just doing it in the dark So get a second opinion of somebody whom you respect on the project. Don't soldier through it alone on your project But refactoring can be hard. Oh, yes, it can be very hard, but a lot of other things are hard in life Socialization is hard right socializing with people is hard Hey standing up and talking is hard and depending on the speaker sitting and listening is even harder, right? So a lot of stuff are hard in life. So it depends on how you approach it That's why he had this earplug on was singing, right? There are ways to cope up with these problems, right? absolutely so How do we deal with this? so one of the things is the only thing to fear is fear itself as FDR said so yes It's natural for us to fear when you tell me to go do something that I've not done before or I'm so worried that I Embarrassed myself doing it and natural tendency is for us to get you know fearful But the only way to deal with fear is to really logic. You know what that is one of the things we in this room are Really good at we are extremely logical, right? That's why some of the spouses we have don't really appreciate us, right? Every time they say how about emotion honey, let's talk look at this logically and they don't want to sit with you anymore Right, so it's natural understandable, but let's use it to the advantage in these cases We can be very logical so think about it. How can we do it? So why do we fear things? I thought about three reasons that I can fear about What if I break something that worked? That's a good fear to have Is my change worse than the original code? Sometimes I have the feeling did I improve this really, right? And we hate being embarrassed. It's easy to leave things, you know unchanged. You know what it worked Why do I mess with it? Why do I take you know problem with it? So help me here. I want your thoughts What if I if I break something that worked? How do we deal with that? Writing unit test I'm going to just change that a little bit the reason is sometimes well a lot of times The legacy code is so messed up. There is no possibly a human can write a unit test But that is not a reason to give up. We got to be very, you know We got to really explore it. So my recommendation is deal with it by writing automated tests And why should I write automated tests because before you change the code? Write the test try to get a coverage and in fact what I would do is once the coverage says the area of the code I want to be factor has been touched. I literally break this code and I make sure my test is failing That gives me confidence that I'm actually reaching into that code then I put back the code I had make sure the test is passing now I refactor and make sure the test is still passing Here's another thing to be you know to have credit for a lot of companies don't have unit test on legacy code But they have a fairly decent amount of you know integration tests Sometimes the custom companies may not have but key customers have written a few things go find wherever you can and Run those tests and when you refactor you know that the code does still what it did before Why should we do that and the reason simply is you don't want to fix the code and find out that two things are three things That work before doesn't work anymore Because by refactoring if you break the code then at lunchroom that you will be the person of laughing stock They'll say oh he's going to refactor code again, right? So that's not what you want to you know create ass so make sure the refactoring actually works Is my change worse than the original code? How do you counter that please? Yes, please But you know what it's a good about it if they didn't know it was crappy before they won't know it crappy after you change it Right, so we're good still at least it gives you a little bit of confidence to get going with that, right? So that's the best part about it. So if change is worse than the original code What do you do? How do you deal with that? Exactly how about asking for a review with somebody pair with somebody right you do something you say what do you think is this better? Is this worse so you can always get a ask feedback from respectable colleagues and mentors respectability is important there, right? We hate being embarrassed. It's easily things as it is. How do we deal with that? I got a very simple answer for it. We are programmers. We are shameless get over it Right, if you were so sensitive the first compilation error would have turned you away from programming, right? We take this nonsense every day the compiler continues to spit that you what do you do you wipe your face and continue coding, right? So we can deal with it. Come on. All right. So I'm gonna talk about some simple principles to deal with So let's consider some principles that can help us refactoring. I'm gonna give you about 11 principles, I think depending on how we count it. So let's get started. The 0th principle We got to start with zero, right? We don't do stuff with one in our field because that would be too easy to deal with things So the 0th principle this always drives me nuts. I go to a place and they say you go to the first floor I go to the first floor, then they tell me there's a ground floor somewhere. I can never get this right, okay? So rely on automated tests. That's what you said a few minutes ago, right? So you want to have automated tests some kind of automated tests as much as you can to go back to your point earlier There are certain tools that can go through a code and try to figure out various combinations of input and output so you could use tools to generate some test cases as well It doesn't say the code is correct by any means, but it simply says whatever it did before it continues to do now That's all we can do right and then we can evolve it from there This is most ideal if you can have unit tests But like I mentioned there are times when it's really hard to write unit tests But some kind of an automated test functional integration is good. Yes, please That's an excellent question. My first thing is I This is not about you, right? I hate when people say performance is important and I tell them how important is oh very important Well, if it's so important, where's your test about it? So if anybody cares about performance of a system, but don't have a test related to it. They're just kidding So if performance is very important first write a test for performance and say my code This particular activity should respond within this duration of time write a test for it That becomes your test as well And if the test the test doesn't exist then of course, you know, you need to ask what the performance is But a lot of times what I find I'm kind of deviating from here But when I deal with customers when they say performance is very important I tell them write a test case for it and they're reluctant and then eventually I say tell me what the hard number is and Eventually realize performance really was not that important as they proposed it to be So wherever it is really important back it with the test Otherwise, there's no way to really measure that and keep up with it as we evolve the system Right Oh, no Right, but it is not a very late because you would run these tests very you know quickly and Performance test have to be run continuously as well If we don't run performances continuously then we just don't care about it and we just pretend that we do So so isolate the code if you can and if you will and create these tests So what do you look for? To write good quality code the advice comes from not a computer science book It actually comes from a book which talks about how to write good English This book was written a good 30 years ago I cannot recommend this book enough if you haven't read this book by it and I say it with confidence because I didn't write it So this is called on writing. Well, it's a fantastic book by William Zunzer And in the book he talks about four principles to write good English nonfiction and it turns out I think these four things are the fundamentals of Refactoring and when I refactor my code when I write my code, this is what I think about The four principles he talks about the first one he talks about is simplicity He says things have to be simple Now by the way creating simple things is extremely hard Einstein said any intelligent fool can create something complex and violent But it takes a touch of genius to create simple things simple things are the hardest to find but there's another impediment by the way Who here wants to create something very simple? Because simple is boring Simple makes us insecure Suppose he's my boss or a supervisor. I show him a design and he looks at this and says yeah that looks simple You feel let down You say really you just looked at it. You understood it. You say give it to me. I'll be come. I'll come back tomorrow And the next day you show him the design and he is developing ulcer as he's seeing it and you're like, yeah I took two hours to write it you better take seven days to understand it barely though, right? So we feel good about creating complexity, but it really takes beyond that to create code that actually is simple That's hard. The next thing is clarity You want to create code that is very very clear But you know what I will tell you about everyone in this room, right? We all want to code write code and we are proud of this You showed to the other guy and he's scratching his head until the hair falls off Why do you use shift operator seven times there and then he's like, what do you think? Imagine if you leave puzzles behind to your team, they're not going to develop software They're gonna come to work. They might as well go south Sudoku, right? They're there to get some real work done So make it very clear when there is a deadline looming over the head They want to fix a code. They open the code and they're like, what's this puzzle? He has left behind don't torture people, right? They curse you Right the words they use though. You don't want to take that So just write code they can understand and they thank you. You will not hear it, but it adds you a karma bank Okay, so just do that Brevity Brevity is tricky, right? Brevity doesn't mean just short. I had one guy, you know You want to keep things short in English. He says don't write long sentences We Indians are so good at it. We write long sentence by the time you get to the half of the sentence You have no clue what you're talking about, right? One of the first things my professor said is don't write long sentences. Okay, what's your problem? And then I looked at the papers like oh, yeah, he's right, right? So it writes short sentences in coding similarly, right shorter methods shorter, you know classes shorter Programs anything that can but don't take it too much too much I was teaching a course in Northern Virginia and one guy said how dare you come to this company? We are a great software company and you tell us we cannot use single letter variables. I was like man, I offended this guy I'm sorry. You know what? That's a good practice You know if you can take it or leave it and he said oh, no, no, I was just pulling your leg You should look at our code man. It's single letter variables everywhere and six months later I went back to this company the same guy said oh Venkat. I want to thank you I was like really for what you came last time and told us not to use single letter variables It has made a huge difference. I was so proud. I said really he said we use two letters now There is no way to fix this right so You want the right code that is easy to understand so brevity doesn't mean cryptic Brevity is different from terseness, right? So keep things small That's very important and the last one is probably the most difficult one Because I was doing through this and said humanity We are a bunch of emotionless people logical people Why would he made it to be involved in it and I can vouch for this every time you call a couple of guys and say How do you design this code and they talk about oh you would do this? It's a lifeless computer. They're talking about and the design no wonder sucks Institute throw that away and say hey if you were doing this, how would you do it? Bam comes out a beautiful design because they put themselves into it, right? So humanity is extremely important to create a good quality software. So I think these are extremely good principles to follow So the first principle the zeroth principle is over Rattles code. Oh my god. I cannot emphasize this I'll guarantee you the code you did not write has the fewest bugs Right, you cannot have bugs in the code. You didn't write. There is no way you can improve from there, right? So the code you didn't write but what do programmers do? Before you can turn your head 30 lines of code. Wow. How did you do that? The other day somebody showed me like three pages of code, right? Did it all of that? Well, we are so you know eager to write a lot of code. In fact a great programmer avoids writing code You need to really say do I really need to do that? I'm gonna question that So don't write code that is really not needed that takes a courage to say, you know what? I'm not gonna write that I don't need that right now So programmers end up writing as much code as a restaurant serve food This is one of the biggest problems by the way You go to the restaurant they give you a food like you're not gonna like you're going to go into it You know decide for the next one week eat a beta, right? Why why should I have so much food, right? And same thing with coders Why should I write all that code? I'll share with you an experience. This was a delightful. I came back from international trip I was starved. I was hungry. I went into this restaurant sat down and I was lonely No sit down gives the menu and I said to this guy I want this this this and this in a very straight face this guy looks at me and says Who else is with you I? Said I'm alone and he said that's all for you I said, yeah, that's all for me and then he kind of smirks and says you won't handle it I was angry for a second, right? I said excuse me and he said I bet you you cannot eat that much food How do you know about my appetite and this guy says, okay? I'll hit a deal with you I will give you half the food you asked for you decide to pick which half you want and if you finish it And if you want more food the rest of the food I serve you is on me I was like Okay, fine. Let's take it as a challenge. So he gives me half the food. I ate half of that And I said, I'm sorry because can I bring you more select? Please? No, but you know what he did that day He earned my business He earned my respect He could have wasted the food and earned the money But he had the wisdom to say you don't have a clue what you're doing. I'm not gonna sir I was not like asked for alcohol or something like that, right? This is plain food That's all and I want programmers to have that kind of courage to say I don't need to be writing this code, right? So take that courage Code you don't write of course is easier to maintain. You don't have to maintain This is one of the beautiful code that I always like to remember Perfection is achieved Not when there is nothing left to add But when there is nothing left to remove So a great way to improve code is to remove it What did Michelangelo do? He took a marble slab and what did he add to it to create this beautiful naked David? Nothing absolutely all that he did his time was to tactfully remove and That is one of the most important things to remember a lot of times We are so eager to add stuff when we really should be focusing on what can we remove? Don't write clever code now if you ask me in my experience. What has gotten me the most trouble into it Has been clever code. I Remember in one of my books as I was writing it. I did something very clever. I was so proud of it I said isn't this beautiful about two weeks goes by and in production the book is in production Somebody downloads the code and has a problem and eventually the publisher comes back to me and says what's up with this? And I look it's like oh dear I remember how clever I was that day and that was just not one time by the way Every time I write clever code. I've got into trouble But the good news is I've learned from experience now when I write the code the minute my brain says this clever I delete it. I don't want this to go out anywhere, right because clever code causes problem So don't write anything clever write something simple and make it clear, but not clever. That's very important Make it small and cohesive when you're writing code Ask yourself is my code doing one thing and one thing well If your code is doing so if I ask you what is my code? What is the code do and if you say my code does this and time out that would end Give you away. It should be one thing that don't put comma, right? So there's one thing it should do and that is what cohesion is that it is focused narrow and does one thing well So why should we not write long methods? How many of you believe writing long methods is a good idea? Nobody okay usually one person raises the hand. Oh, she no she was scratching her head. Okay, fine And I would ask this person. Why do you think writing long methods is good and this guy genuinely good reason? He would say because the code runs faster And you know what he is right But that's when Nixon was the president lot of things have changed since then computer architecture, right? This person didn't look at a book since then right still so who's the president? I should have asked him Nixon No, no, no things have changed right watergate dude, right? So the point really is that is no longer true. There is compiler technology optimization technology How many of you? Have seen long methods at work Look at that This is called cognitive dissonance Three one here knows writing long methods is bad bad bad and yet we see long methods at work And you know why because I know nobody in this room has written long methods The guy's writing long methods are making the methods longer at work today Not coming here, right? What a sad story. They're sitting there behind your back making your methods longer This is atrocious, right? But we all know writing long methods is bad idea, but why is writing a long method a bad idea anybody? What is that? Wonderful hard to reuse don't say reuse people think it's good right hard to reuse. Okay. What else? Hard to debug it never confirms to single responsibility, right? So, yeah, so no single response SRP's single responsibility principle. Okay. What else? Complex okay complex. What else? What was that? Hard to test Hard to read this guy has hopes. Okay. All right. What else? But throne. Okay. What else? What was that? Oh Yeah Okay, where does it start and end? Yeah, hard to see the whole thing. What else side effects beautiful. What else? Leads to Duplication isn't it you got this wrong method somebody said reuse right right there in the middle is the code you want But it's right embedded down there. What do you do? Oh wait a minute You copy that and stick in another long method. So it leads to go duplication, right? It's hard to maintain this list by the way goes on and on and on and yet People write long methods Scary isn't it we all know this is terrible thing to do and yet we see it you say well, okay Wait, we got to fix this. What do we do? You say I've told all the things to my colleague. He doesn't listen I got one last one last Effort what was that never works? Yeah, but just because it works unfortunately is not good enough, right? Will it continue to work? That's where the problem is right because unfortunately Software has to evolve My my my RAM is so small. I don't retain what I said. He expects me to remember stuff. I say, okay, all right, so What was I saying? Okay, so anyway, so if you're maintaining so you have this last ditch effort, right? So you go to work on one Monday sit down at work Don't talk just continue to code and your colleague comes to you and says how was how was the weekend? You could tell your colleague. Oh the weekend was great on Saturday. I went to the movies and Sunday I went to the park and your colleague may say really which movie did you go to? You can tell the movie name and then you can talk about a scene in the movie, right? But don't do that your colleague says how was your weekend? Oh the weekend well at 7 o'clock I got into the car turned the ignition on but it in reverse took it about five feet away Turn to the right turn to the left would roll around stood at this light There was a bird over there. I was watching and then I turned left Just keep talking like this for a while and your colleague is in a panic mode and then says have you gone crazy? You say no, I thought I'll tell you how many weekend was like your right code Right Because that's where your colleague writes code, right? Where does it start? Where does it end? And what do you do in the process? Nothing is known. You just Plowed through that's not the way you communicate with people. You say on Saturday at this Sunday I this then you dig into the detail where you are interested in that is exactly how we should be writing code So long methods have no place and how long should a method be? Somebody says 20 lines of code another guy says 10 and the Ruby guys are like 10 is too long Right seven lines three lines. Well, it doesn't matter how many lines one thing I would say is you must be able to see the entire code in one window without scrolling Don't don't lower the font size right But it's more than the size of the code by the way you want to make sure That the code is in one level of abstraction That is the most important thing when you get into a code There is one level of abstraction like for example if somebody tells you how was your weekend? You talk about major things you did in the weekend went to a movie went to the park You're not drilling into any of these details more in in a very short sentence And if you want to talk about which movie it is that is a second level of abstraction Like which corner Street the park was at and if you want to talk about one specific scene in the movie That's like one particular tree in the park So those are multiple levels of abstraction and writing code exactly involves that we need to focus on that So that is something important to keep in mind and we can avoid having long methods if we do that The fourth principle is eliminate duplication Because code duplication is hard evil to maintain and it I was I was speaking to a company in Hyderabad I was talking about how bad the duplicated code is this guy. This programmer was in complete sync with me He said you know Venkat you're absolutely right In our application we fix the same bug every two months That's it. Oh my god. Does somebody actually run over and put the bug in back in the code He said oh no no no no this code is duplicated so many places. We keep discovering it. I Said oh my god. How does it feel? He said oh that sucks And I said of course when you find the bug and you find it's duplicated you do remove the duplication refactor the code, right? He says what a great idea There's no end to it if you don't remove duplication that's opportunity for refactoring So every piece of knowledge must have a single unambiguous authoritative source of Representation in the system and that's what the dry principle is all about Eliminate dependency. Let me emphasize this. I am not asking you to invert the dependency. I'm tired of that People want you to do inversion of invert dependency. What does that mean? Brr comes a inversion framework. Please. Thank God We don't need to do that Don't Invert dependency get rid of it. I was in speaker comms con a couple of years ago narration ranged one in Philadelphia I was quite listening to a group of guys having a good chat and they were all saying oh We would be doing more unit testing if only they were more easy to maintain And a few minutes later I kind of pitched in and I said hey, maybe guys your unit testing is really hard Maybe because your design sucks just saying that I offended everybody in the room. They were like angry What do you know about our design? How could you say that I said because I design my design sucks all the time I thought you guys are like me and Then they said well, how would you design this we talked about this for a few minutes and I blocked about it after that weekend and my recommendation is Knock out dependencies before you mark out dependency So we most of the time so eager to mark dependency We fail to realize we don't need to be marking if we can knock it out So the first design refactoring technique I would use Is to eliminate dependency Not inverted because the eliminated dependency Goes away. It doesn't bother you anymore. There is no marking at the end of the discussion Half the people were still mad at me and the other half said interesting I should go back and try this because I think there's opportunities for me to actually knock these dependencies out By you know redesigning the application So that is one of the things if you want interested just google for knock out before you mark out And you can look at the blog entry and read more about it The sixth principle is make comments redundant and remove. I cannot tell you how much I hate comments Comments are devil's work I I'll tell you why comments are such a bad idea. You I'm sure you have seen your share of comments, right? The other day I was looking at a piece of code and and this guy of course very genuinely interested in commenting code A class my class whatever that class was right and then of course comes the wisdom public my class Constructor Right Very useful I was looking at this like dude if you don't know it's a construct. You have no business being there, right? If that is not enough then flows even more wise things I plus plus Increment, right? I'm so thankful because looking at it. I was not cheer, you know, once you go beyond a certain age you're like Is that a plus plus or a star star, right? So Very useful. Thanks for clarifying, right? Why do people do that? I'll tell you why They're not they're doing not because they want to it's because they have corporate police and the corporate police says You will document the code and the genuine good programmer says What if I don't know bonus for you? Oh commenting, right? Because I mean one bonus too will follow What's a big deal? I'll do it. So the corporate police does that for us, right? So Don't write comments like that. So why don't you the comment really be there? Yep, please The docs are good for external users, but don't get me started on that The other day I was looking at a java doc The method name says pass through this was middle of the night Honest to god. I didn't know what pass through was I went to java doc and it said this method allows you to pass through What do you do? So let's not even go there, right? Sorry Okay, so Right executable documentation So, you know, here's the feeling I really get angry about comments code Should be self documented Commenting a good code is like explaining a good joke One rule of thumb you should never do this right you tell a joke and and ravi says What's funny about that? The best thing to do is you say never mind and you move on. Here's what you don't do. Let me explain to you ravi And you explain the joke and he's like and what's funny about that? So you say a joke and people don't get it What do you do you say never mind and you go home quietly that night and you refactor your joke And you say why did this not appear funny to these guys? Then you go to a fresh set of audience and try it the next day If they get it you did well if you they didn't get it Don't try stand-up comedy. That's not going to work for you, right? The point is a good code is like that And of course there is places where you want to express what it means So a good test is worth a thousand comments The seventh principle Makes sense in seconds not minutes hours days weeks. I want to throw a couple of things at you Look at this code real quick. I want you to measure the amount of time it takes you to understand this Raise your hand when you know how this code works. Here you go Most of you're still reading that's already timed out. Okay, so slowly is raising the hand and that too reluctantly, right? How many of you what about this one here by the way quick? We can understand fairly well, right? because this Is did you notice one thing? This code Is at several levels of abstraction. Did you notice that? We are going multiple levels of details. Whereas this says I'm going to be at one level of detail So which of these two is a better version? The second one unless you're a consultant writing code by the number of lines of code you write, right? So Let's burn that code We have to write good code, right? So make it easy to understand very quickly A white primitive obsession We are at this point where we write to like write code at the lowest level And we have to really work hard to remove that. Here's an example is spelling correct that itself is spelled incorrectly File equals new file And then it says for each line go through this is by the way groovy code I was looking at this code. This was actually code written by somebody As I was looking at this code, it took me a couple of minutes to understand And once I understood this code, I was like really? And I rewrote it and that was exactly the same thing and I'm relying on a higher level api Avoiding the primitive obsession. Sometimes you just want to be at the very low level This is one of the most important things for me check in code frequently how frequently Within minutes not days not weeks not months within minutes Now I'll share with you a just a story real quick before I go with this I was pairing up with the programmer. I was the mentor in the team. This is the reason I love mentoring Because very quickly I've become the student. I begin to learn I was pairing up with this guy and we were supposed to refactor a class that was the You know facade the database and I'm thinking about this my god This refactory is going to take about maybe four five hours And it was about two in the afternoon and this guy sitting next to me We were in you know, holland. I was on a project there and the guy sitting next to me says all right Let's start refactoring. We did a little bit work immediately runs the unit test all that unit test passes And then he kind of looks at me says now I should check this code into the version control right And I smiled at him and said you said the right thing. Here's a candy for you But tell me why you should check in the code right now. He said I have three reasons. I was like wow This dude has thought through this three reasons. Tell me what those are He said the first reason if we continue to work with this for several hours It'll become a merge hell Number one rule of programming. You should never receive merge hell. You only give it And he's like yep, I said great the second problem We are trying to refactor this and when we are done We realize this is not comparable with the rest of the system But if we keep checking this in you know often if it doesn't go well with everybody else They can scream and immediately we can revert and go forward I said excellent. What's your third reason? He looked at the water and said I have to leave in 50 minutes And he said when I come back in the morning chances are I have other things to work on You could pay it up with somebody else and continue to work on this because I know you have no life But I have to go and then he said when we come back in the morning We could pick it up again or somebody else could pick it up and to me that is extremely important You should be able to leave your work in the system Where somebody else can pick it up and run with it if you have japonized the entire system Some companies you've probably heard this guy sends an email or an announcement Nobody compiled the code for the next hour. Why because I'm refactoring. No, that's not refactoring. That's messing it up So you should be able to continue to evolve the system along the way So let me quickly wrap up so frequent checking is extremely important. I cannot emphasize it enough The last principle keep code at one level of abstraction. This is called a compose method pattern So when do you refactor? Generate a general awareness keep looking for code. By the way, what a beautiful metaphor Smelly code awesome metaphor isn't it? Ken Beck is awesome. You know why this is the wonderful wonderful metaphor You come and sit next to somebody and you kind of twinge your nose What's that smell? And guess what happens about five minutes later You don't feel it anymore Right That is why code smell is so evil You join the project and the code sucks you program for three weeks You don't feel it anymore and you write code like that Next day you come with much more smelly shirt, right? I won't feel his smell anymore Right and that's why this is a fantastic metaphor Somebody from the outside comes and senses this and this guy better leave quickly. Otherwise gets too used to it So look for these and refactor continuously So code is messed up beyond any reasonable repair. Don't refactor. It's too late And if you're in the middle of fixing a bug then don't refactor fix the bug then come back to refactoring If you don't see a clear benefit to a particular refactoring, don't do it So when do you refactor before fixing bug or after fixing a bug before enhancement or after enhancement ever in middle And if you think you can improve the quality of code and if you want to make it easier to understand the code refactor it So how do you refactor take very very very small steps? Extremely small steps are very important So devise a sequence of small steps and within these small steps check in the code continuously Along the way passing the test be continuous not episodic You want these to be very small Flow of operations aim for bite size improvements when you say I want to refactor this What else can I do? How small can I do and keep coming down to it? Never refactor code. That's not an aversion control Everybody's code here isn't aversion control, right? Yes, thank you. Okay Yes Don't hesitate to throw out change. I want to emphasize this You need to have courage to say, you know what what I put in is sucks. I'm going to throw it away and start over I guarantee you your code will be much better when you have the Have no fear to you know throw it away one more reason to check in code When the code is checked in I can go wild with my ideas. I'm not worried about losing my code If I'm not checked in code and somebody says isn't this better? Oh, no, no, don't touch it It's not checked in yet, right? So check in code frequently for that So to wrap this up, here's a flow chart, right? How about that? I identify the code to refactor. That's the first step All right, that's the code. I want to refactor. What's the next step? Do you have tests? No Right test isolate code if needed Okay, we got test. What do we do now perform a small Yet a useful improvement All right done. What do I do and should all the tests pass Yes, they do. What do I do? Check in your code rinse and repeat Thank you