[Music] let's talk about a topic we of course are fairly familiar with which is refactoring we've heard about refactoring you've done refactoring but what I want to talk about today is how do we really approach refactoring what I'm hoping is you can walk away with a few different things that would help you to approach this maybe a little bit more differently or a little bit more Intently and then be able to do a better job at refactoring when it comes to refactoring what is really refactoring refactoring is um here's what modern Fowler defined it I'm
paraphrasing his words he said refactoring is the art of improving the internals of a code design of a code without changing its external Behavior I think that's what also gets us into trouble with the boss right because the boss says let me understand this you're Going to take the time to refactor and when you're done the code is not going to do anything different uh tell us why we should pay you to do this so so we need to be able to understand why we want to refactor he says it's the art of improving the
internal design of a piece of code without changing its external Behavior but notice he also very carefully choose the words he didn't say it's the engineering off no he didn't say that he didn't say it's the science Of no he said it's an art off the reason it's an art office you got to improvise you have to consider the different things and and evaluate it and it involves a bit of opinions you bring into it rather than simply being an engineering approach but the question is how do we really approach refactoring I'll talk about what
I will not talk about in the stock first I'm not going to talk about the exact refactoring technical things you would do like for Example you can do extract method refactoring you can do this you can do that the reason I won't talk about it in two four number one there are a lot of amazing books and articles and talks on exactly that and and they've done a really good job than I can here secondly the way I am wired is I never ever try to remember a laundry list of things that I can do
I don't say here's a list of techniques let's follow from them that's not the way I work that's not the Way I think and and so instead I will go to something more fundamental how do we approach refactoring now when it comes to refactoring uh refactoring honestly liberates us because when I'm writing code I don't have to be under pressure to do it in a perfect way not because I cannot attain Perfection it's because I don't know what Perfection is in a certain context and as a result if you really try to make things really
uh you know perfect you may actually end up Making things actually worse in the long run so for that reason I would say refactoring gives us this beautiful opportunity where we can create something and come back and we can improve on it so for that reason I'm a big fan of this Mantra that I follow which is make it work make it better real soon and when I say real soon I'm not talking about seven months from now or even seven days from now so one of the tenets of test driven development is The cycle
of red green refactor so you you have a failing test you write minimally code to make it pass and then you come back and refactor it and it's impossible to get it right on the first right so you want to write something and you want to run it see if it really meets the expectations but before you move on immediately Factor it make it better so make it work make it better real soon is generally a good practice to follow but also we at some point we Need to become very honest with ourselves because if
we don't uh be honest then we turn into somebody else over time so it's perfectly okay to be proud about what we do we don't have to clutter what we do if you ask me what what do you do I'll be honest about it I'm a programmer that's what I am I love programming and what do I do every day I write code because I'm a programmer and I solve problems for writing code by solving you know problems so it's okay To be a programmer I was talking to a person recently and and I asked
him how things went and he said well I've refactored this code I said you refactor the code tell me what you did and he explained what he did and I looked at him and said looks like you fixed a bug and he said well yeah I fixed a bug well then why did you say you refactored it instead of saying you fixed the bug he said because it feels better to say that I refactored the code right I mean this Is exactly what you see people right you go to them and say what do you
do I develop microservices and you find out what they do it's not micro Services why you're telling you it feels good to say I'm Microsoft I mean how can I sit in a table next to somebody and tell them I'm developing an Enterprise application right telling them I'm doing microservices makes me feel better we lie every day there's no reason to do it we're fixing the bug you fixing a bug Say that they're fixing a bug you're making an enhancement to the application say that you're enhancing application refactoring is different refactoring is where you take
an existing code you're not fixing bugs you're not making enhancements you are improving the design of the code the question is why and the answer is extremely important but simple refactoring is done because it's got an economic impact it is it's got an economic impact you want to Reduce the cost the time the effort it takes to modify the code in the future so you are going to take the time to refactor it you know I travel a lot so I'm in a you know different places around the world every week and I would go
to a client side I'm working a site I'm working with them during the day in the evening I would uh you know take my laptop or a book and I would go to a restaurant and I would start you know sit down there order some food and I Would start working until even eventually the restaurant will come to me and say we close the restaurant an hour ago we've been waiting politely we have to kick you out can you leave so now during the you know over the dark streets I'll be walking back to my
hotel and I always pass and think about it or in the busy evening as I was going to the restaurant to have a meal the streets are busy people are you know having a lot of fun I would look through The door and there are restaurants and families and friends gathered and having a meal and then now the streets are empty I'm walking back to my hotel and I would look through the same windows and what I would notice is that the floors have been cleaned up and the chairs are put on the top of
the table and in some restaurants they have cleaned it out they have set the table for the next day and they are all ready and I will always look at this and pause and say the Restaurant has cleaned up everything the barber shop has cleaned up their stuff the store has cleaned up their stuff and then I talk about I think about us the programmers we leave home and the cursor is still blinking on the debugging console right and the next morning you come in you push the pizza away from last night and you continue
debugging from there right and I always say what if we had that discipline where at the end of the day we cleaned up our stuff We did a reset and we said today is done I'm going to start my work tomorrow and as it turns out you may say gosh we are not barber shop we are not restaurants we do engineering well guess what I have seen engineers build buildings and the bad ones leave a mess the good ones clean up at the end of the day so you can actually safely walk without a nail
protruding in a bottom of your shoes and so we can be professionals as well well refactoring is an opportunity to kind of Do that resetting and think about it well good old Frederick Brooks once said he said go ahead and build a software system and when you are done building it throw it away and start over now you have a chance of building a relevant system now try telling that to the Boss by the way you go to the boss and say do you think Frederick Brook was a great software developer and the boss says
aha I've read about it well guess what Frederick Brooke said he said build the Software don't deploy but delete it right this is the best way to get escorted away from the building right because you cannot delay the system practically does it mean Friedrich Brook was wrong to tell us to delete well no he was absolutely correct but what if you do a micro deletion rather than a macro deletion you write that little code but refactor it before you go forward that gives an opportunity for us to keep improving what we do that's Another area
of Improvement what we can do as well so with that said let's talk about how we can approach this so we talked about what's refactoring and I'm going to say it's a genuine desire to improve the quality and the design of the code but why the simple reason is you cannot be agile if your code sucks that's the simple nature right so you are sitting in this meeting everybody is talking to each other and now they are talking about having to make a change to The XYZ module and immediately you perk up and say excuse
me did you say you want to make a change to the XYZ module and they're like uh-huh we want to change the expression module like no don't even bother touching it because you remember the last time they touched the XYZ module you couldn't go home for the weekend you had to be at work trying to fix this mess and now you tell them no no we can do anything you want to but don't touch that module right and you Cannot be agile well if your code really sucks if you want to be a agile if
you want to respond to change you need to be sitting on a good quality code but of course we know we cannot create good quality code in the beginning not because we are incapable because we have other things to really do what is programming I mean have you ever seen anybody do this you give them a problem and they say no problem and then they sit there and then they just type away And then they say I'm done and they walk away and you tell them have you tested it like I don't need to test
it I wrote it it's going to work and they walk away has that ever happened to you no right how do you program normally you start writing code you bang on the keyboard you scream a little bit you Google search a bit and you're thinking about it is it the way it works right that's the way it works right uh my wife always tells this one day she said venkat you Are a very polite person you don't use bad words at all in in talking to people and I said yeah yeah that that's that's I
don't believe in saying bad words to people and said no no but and the butt is always a scary thing that comes and she said but and I said but what and she said I you know I work in my basement and she said occasionally I would come to the basement because I want to get something in the fridge you don't even know that I came and left but and you Will be coding and the amount of Filth that comes from your mouth when you're coding I'm like I'm sorry dear but that's called programming right
so when you're writing code you're a different person all together because the code is what you're communicating with not the person but that's the whole point when you're writing code if the code notice of not good quality you cannot Embrace change it becomes really hard so it's important to have the good quality code That is absolutely essential but you say wait a minute though but it takes time but guess what anything useful in life takes time we have to take the time to get better at what we do that's just the nature of what we
do it it takes time to do almost anything in life so the first law of programming says lowering quality lengthens the development time so if you really want to go slower write poor quality code because poor quality code will really make you go slower but if You want to go faster you have to really write better quality one of the slogans I say is is this sometimes you have to slow down in order to gain speed this is a bit ironic right so sometimes you have to slow down if you want to gain speed because
if you don't slow down at the time you need to slow down you may end up in a ditch and this is not going to help you so there are times you want to slow down so you can gain speed as you move along that becomes very necessary So having said this though so the question we want to ask here is how can we really get better at it so we want to refactor in order for us to be able to be cost effective and in making the change and so we want to be able
to effect change and embrace change that's the reason we want to continue to refactor that's the real purpose of refactoring so one of the beautiful comments by Ableton and Sussman says programs must be written for people to Read and only incidentally for machines to execute what a beautiful part isn't it you want to write the code for fellow humans to understand more than a machine to execute and we need to really keep that in mind so I'll tell you one more reason why you want to improve the quality of code that you are writing and
and the one more reason that you want to move the quality of code is code is how we tell our colleagues how we feel about them uh so What do you tell your colleagues do you tell them I love you all or do you tell them I hate you all the code is how you communicate that right so at the end of the day you want to really keep one thing in mind we talked about economics sure but but coding is an act of empathy so you want to really think about that think about the
person that is going to look at the code right what do we do in a civilized world you're walking through the door and you're going that that door You're going to push that door to open it but what do you do as soon as you push the door and step away ever so gently you hold it just for a moment don't you why because you don't want the door to swing and hit the person behind you that person behind you may be a complete stranger but you have that empathy deep down in your mind and
as you push the door you hold it just for a minute sometimes you glance to see if there's anybody and then you walk away But the key is this every time you push the code that is somebody pulling it on the other side you don't want it to hit them on the face so always think of the person who is going to read your code that becomes absolutely necessary for us to think about it so given this of course we want to think about the reader of the code and we need to evolve an incrementally
develop it so a code that is hard to understand is worse than the code that you don't even have access to Or is lost so you want to be able to modify this code and move forward so you want to be able to evolve the code because we constantly change software that's what we do so like I said make it work make it better real soon and refactoring reduces the risk and leads to lightweight pragmatic design so a refactoring gives us an opportunity to come back and evolve to come back and change to come back
and improve and that becomes very very valuable so as I said Earlier Martin Fowler talks about this as an art of improving the design of existing code and it's a process of changing a software system he says in a way that it does not alter the external behavior of the code yet improves the internal structure and that's what we are trying to achieve in this case so strike a balance do I need to refactor or not remember it is taking you away time from other things you are going to do so how do you know
if you want to Refactor a code or not let me first tell you this don't refactor a code because you didn't write it that's one thing we need to be careful about right sometimes the developers are like I'm going to change this code why I don't like it why don't you like it because I didn't write it well sorry you know you're not going to write every piece of code you have written and and sometimes you need to keep in mind you are not the same you you writing code two years ago I hope is
Very different from you writing code today because you have learned and improved and isn't it the other day I saw one developer was so angry he was complaining endlessly about a piece of code until somebody pointed out the Version Control shows that he was the original author of the code right he's like gosh I don't even remember writing this code so sometimes we get really angry at code so don't refactor because you don't like what you're saying you Got to be able to convince yourself and others why you want to change it so consider the
impact of the change you're going to make get a second opinion go to a colleague and say hey I'm going to refactor this code what do you think and three things can happen happened right he or she is going to tell you yeah go for it that's a good idea you then what you're thinking is good go for it or they may say hey I just wasn't a meeting we're going to throw away that system Into to listen to months don't waste your time refactoring it or oh I just know that we uh you're going
to have a replacement for it or we have an alternative already and work somebody else is building it don't you know spend time refactoring it so don't don't do it without consulting and don't do it alone it's a great experience to pair with somebody and and do the refactoring refactoring is hard well yeah like a lot of things in life is hard driving is Hard uh the first time I started driving the Empire City was scared that I was driving so driving is really hard speaking in front of people is really hard uh you know
socializing is hard and awkward for a lot of people and and so there's a lot of stuff that is hard for a lot of us now of course you know it depends on how we approach it and so how can we approach this as uh Roosevelt said the only thing to fear is fear itself so if you are fearful of doing Something address that fear head on ask yourselves why are you afraid to do it rather than trying to avoid doing it so you know don't fear what you're going to do including refactoring so but
why do we fear refactoring these are genuine reasons isn't it the first reason what if I break something that actually works is that a reasonable uh fear right you're going to refactor a code and you finish refactoring and you say I'm done refactoring and they find 20 things that Don't work anymore the next time you say I'm going to refactor everybody comes to the defense not to you of the code right and they tell you stop please don't and they don't want you to refactor is is the change worse than the original solution that can
sometimes be a problem right I finished the changes like isn't that awesome everybody's like no right this is worse than what it was why would you do this and we had been embarrassed and it's easy to leave things alone you Know what it's there I didn't write it but if I change it then I become responsible I don't want to take the response but I'm going to leave it so let's think about these things uh what if I break something that actually worked how do you think I can cure that fear we'll have test cases
right run your test cases make sure the code is working modify the code rerun your test cases and you say what is this thing called Test case you keep talking about right where do I buy that from which stores do they sell it well sometimes you're refactoring the code so you can write those damn tests in the first place right so my recommendation is if you have automated tests use them if you don't have automated unit tests look for automated integration test if you don't have automated Integrations there's come up with at least some kind
of a manual test that you can run and get the Feedback and then modify the code so the key here is not that you need to have a test the key here is you need to have a feedback that's the key somehow you need to know the before and after are still the same uh if if things are worse than the original code how do you cure that fear what if this is poorer than what it was what can you do what was that what was that said again the time processity no no but what
if This is worse than before how do I know it's not how do I cure that figure fear yeah go to a colleague and say can you take a look at this can you review it can you pair up with me and work on it but having another pair of eyes to look at it is a great feedback right so that can help uh we hate being embarrassed it's easy to leave things as it is how do you deal with embarrassment you know the answer for it right as programmers we are Shameless already Right isn't
that true anybody who wrote code anybody has ever written code what did you do you said I want to learn programming and people learn to you like really have you ever written a code no I'm going to write programming and you come with this eagerness to write programming right and you write your first code and when you say I wrote the code and the person next to you says rewrote the code dude did you ever compile this you're like oh I Need to compile it and you ran the compiler what did it do literally It's
Pat on your face right it said oh and you're like my gosh what's that and you take this and you drop it and they say that's your first compiler error if you got embarrassing insulted the programming field would never have existed the people who wrote the code removed the spit and they wrote more code And 10 years later you write code and what happens it spits more and you're like bring it on right so that is what we are right programmers are the bravest people on Earth we get scolded spit on every abusive word you
can think of the compeller throws at us and we are like still we go back and we work with it right and when it finally works just for that five seconds we get really excited before everything falls apart again this Is the beauty of what we do right absolutely so get over that okay so let's consider some principles that can help us to refactor there's I call this a zeroth principle so what's the zeroth principle uh rely on automated tests ideally you want to have unit tests if you cannot have unit tests rely on functional
tests or integration test if you cannot have that look for some kind of a manual test what you want is a feedback loop here's what it did before Here's what it's doing but here's one other thing once you run your test what whatever form the test is break your code and re-run those test cases manual or automated make sure the Test shows you that your code is broken why because you don't want to have a false positive oh my gosh everything is great but the code was not even testing the code you're going to refactor
once you know it's actually has the eyes on the code put it back together make sure the test Is passing again manual are automated and then start refactoring right after that so the first thing is never refactor code that is without any kind of a feedback mechanism that's the first thing uh second so what do you look for surprisingly a good advice can come from really different places but for me one of them is a fantastic book that I read or years ago it's a very old book but it's a book on writing good English
and and this is a fantastic book on how do You write non-fiction and this book talks about uh when you're writing English you're writing maybe an article a book a blog post doesn't matter anything that is not a fiction how do you what do you focus on the author of this book William zinzer distills down to four principles as I was reading this book I said to myself oh my goodness these are not just principles for writing good uh English these are for writing code as well he says keep your Writing really simple uh the
second thing he says is focus on clarity now Simplicity and Clarity right so if you think about Clarity when you look at a code if there's no good flow in the code it's very difficult to understand the code so same thing but Clarity is important a brevity he says shorter chapters are better than longer chapters short of sentences that are better than longer sentences same thing we talk about right shorter functions are better Than longer functions shorter classes better than longer classes shorter application code is better than longer application code and then he talks about
Humanity as well well and and you want to consider Humanity when you write English well we talked about this earlier how humanity and empathy are really important for what we do the next thing I would tell is the first principle I call it is reduce code and so don't write code that is really not Necessary I'm a big fan of this minimalism do you need it do you need it do you need it uh we call this the yagni principle you aren't going to need it so if you're writing some code and you don't really
know you need it don't write the code I have a silly metaphor if you will and the metaphor I'm going to say here is I'm going to say code is like people on a crowded train so if you think about it right when you have a crowded train filled with people what Happens the people in the train cannot come out and you cannot go in and in a train is overcrowded code is like that you have have a lot of code it becomes harder to write code but if you have a minimum amount of code
you can much easily write code so you want to really reduce code as much as you can that's absolutely important so don't write any code that is not needed and and code you don't write easily so hands down the code you did not write has the fewest Bugs in it right so if you want to remove bug remove code that's the easiest way to do it right so you don't need to write code and it takes courage not to write code I remember this experience I would never forget I say courage because of this I
I came from an international trip and I was starving like I was hungry and I went to a restaurant and I sat down and the waiter nice guy came and said what would you like to have and I said I want to have This this this and this and on a very straight face he looked at me and said I'm sorry but who else is joining you for lunch and I said what do you mean I'm here alone and he said all of that is for you and he kind of he sized me and I
said yeah I'm hungry I want all of that and he said I won't serve you that much food I'm like excuse me I'm here to order food and you won't serve it to me and he said how about I give you a deal I said I like deals what do you have Yeah he said you tell me two things you want I will serve you that if you finish those two things and you still want food I'll give you the other food with no charge to you I said I love this deal let's do that
and and I ordered two items out of the four items I wanted to get he searched me the two items I managed to finish half of that and he came and said so do you want me to bring more food with no cost to you I said no thanks for feeding sense into my mind That's the courage you want what if we can tell you or you know a product owners and your business analyst I am not going to write that code because I don't understand the requirements yet right that's courage instead hey what are
you doing I'm busy right now what are you doing I don't know but I got to get this done right so we tend to really focus on writing code instead we should focus on solving problems not on writing code that's very essential so the first Principle is reduce code as much as you can and here's a beautiful quote Perfection is achieved not when there is nothing left to add but when there is nothing left to remove so a refactoring is about removing stuff you don't want you know I I'm working on a book right now
and I went to a a person who is going to give a feedback and it's a humbling experience I'll tell you this I've written many books but it doesn't matter it's a humbling experience I Wrote the chapter two weeks ago went him last week and I gave him the chapter and said review it and his review was I'm gonna take this chapter and start removing things and I worked with this review and I gave it back to him on Monday and we and again we went through this and he said let's remove more and so
we've been removing things from the chapter not adding things to the chapter but every time we wrote something the chapter is becoming laser focused right It is getting directly to what we want to talk about that's exactly what you want to do in your code ask what can I remove not what can I add so removing things really gives you the focus and removes the Clutter and you're able to focus on it you want to definitely do that as well the second principle avoid clever code keep it simple make it clear not clever raise your
hand if you have ever written clever code in your life oh come on no You are don't write code at all then right let me try this again raise your hand if you have ever written clever code in your life really the other people are just a parent they won't raise the hand right you maybe they're never programmed in their life everybody writes clever code isn't it where do you write clever code honestly why do you write clever code because it feels good right it feels good you take a code you Turn to your colleague
and your colleague says yeah that looks simple you feel let down you're like let me let me let me come back tomorrow and the next day you go back and say here you go and your colleague is like hmm I'm trying to figure it out you're like yeah right I mean this is why I recommend that you hire the interns because interns are Awesome when they come and work in your company don't send them alone go with them to campus and hear what they are saying and they will tell their colleagues right hey what do
you do I interned with this company really how did it go I mean these people are genius I didn't understand anything they are doing right we love writing clever code and you go to Mom and say Mom I wrote code yesterday and nobody understood it child I always knew you're smarter one among the group right we have this misguided notion but it's important going the opposite direction we want to write clear code not clever code and and nowadays when I write code my little brain says oh that's clever I delete it right away and I
start over I want to write clever a clear code clear code communicates much easily easy to understand less error prone easier to maintain as well Third principle make it small make it cohesive cohesion is a very important principle we want to keep in mind so you want a piece of code to be narrow and focus and do one thing and one thing really well that's cohesion and you want to make the code really small why because a code that is cohesive changes less frequently a code that is not cohesive changes more frequently not only that
it's more expensive to change it as well because when you go to make The change to the code there are Parts in the code that are irrelevant and it's incredibly hard to change it I'll give you an example of cohesion when I was a kid my Mom and Dad tried really hard to teach me cohesion as a child I would come back from school and I'm eager to go out and play on the streets who want to be in the house being lectured so I would come in and I would throw things into a you
know into a cupboard and run away because throwing things into a Cupboard is the fastest way to put things in a Cupboard right everybody knows that and if you ever open the cupboard you would see everything in there my lunchbox my socks my clothes my books my play items think of it sometimes even a fork and a knife would be there but it was optimized to put things in the minute I need a sock it's a different story you found a blue sock you cannot find the other blue sock and for 10 minutes you are
trying to find it And you may wonder if you don't find things what you do this is why you are part of a bigger family right you got many brothers and sisters you can use their help I want one more sock which is blue in color you have an army of people searching for it this doesn't work really well and but that's the way I kept everything in one place throw everything together and mom and dad said you don't do things like this you keep your books over there you keep your Socks over here like
why would you do that this is fast right to throw things in I know you know you're thinking my gosh this sounds really terrible how did this guy turn out to be the way he is I got married and that took care of everything for me after that right nowadays there's discipline right things belong here don't put things in mom doesn't live yes yes ma'am when you put things by in the proper place right so the point really is you keep things in The like things are together unlike things are apart that's exactly what cohesion
really is that's basically what we're doing so avoid long functions and and you want to really make sure that functions have a single responsibility if it doesn't belong here don't put it there and when we say avoid long functions we are not talking about the length of the function but the number of abstractions in the function that's what you're really Focused on in making it better the fourth principle is to keep it dry the dry principle says every piece of knowledge in a system must have a single unambiguous authoritative representation so you want to ask
the question is this the right place for that particular knowledge for that particular logic or am I duplicating it in multiple places and you want to really as much as possible reduce that duplication in your code that is another thing you look for In refactoring is to remove the duplication and of course illuminate the dependencies and and no don't just strive to reduce dependency eliminate it where you are able to do so so if you don't need a particular dependency you want to get rid of it because the dependencies actually make it harder to test
your system so if you are able to move around your dependencies then that's worth doing so Because that reduces your complexity as well so so eliminate dependencies where you are able to uh make comments redundant and remove them I cannot emphasize this enough um some people have this habit of commenting every three lines of code have you ever seen that right common common comment and why do people write really really bad comment uh and and the reason for that I would say is maybe they had really bad teachers and the Teachers tell them you need
to write comment when you're writing code and you say but but teacher Professor I write good code I'll give you a f okay I'm going to comment from I want right so we are forced with thought very poorly to write comment every few lines of code we are writing now this is something we should be very careful about have you ever seen this before you're reading a comment you're reading a code and the comment says one thing and the code does Something else has it ever happened and now you're like which one do I trust
right and that's where you can confusing this is even worse I joined a company and I worked with them for about a year and and most people who wrote the code had quit they are all gone but but I had the code with a lot of comments in it and a year later the company said we have an event and we have invited a lot of people who used to work with us so I go into a room and Everybody is socializing and and all the comments by the way would have the initial of the
person who wrote the comment right so it's like the first letter of the first name firstly of the last name and I walked up to this guy and I said hey are you LK and he was like so happy he said I am LK have you met before I said no but I've read your comments right because I could hear his voice in the comment that's kind of dangerous right because he's speaking I'm like I know that comment right I know that voice in people that's when you know people have gone overboard with this so
you probably have seen this as well right so you probably have seen something like this you are looking at a piece of code and what did the programmer do the programmer has a function where there is you know code that is sitting right there lines of code as you can see there is code right here so you see this code being repeated Over and over and over like that in a Long Function right you see this but what you notice is right about here little you know this does block right and then a few lines
later you have a bissella does you know another thing block two and then a few lines later have you ever seen code like this right a few lines occurred a common if you want to code a common yes you know what this means it means the person who wrote this code is a bad programmer but not a Bad human being deep down they thought about the person who may read the code eventually and a guilt kicks in and they said let me just leave a comment okay it doesn't feel that bad anymore right so there's
a good person a bad programmer that's what this is but what do you do my recommendation is this and that is first of all first of all the comment why and not what that's the very first thing comment why not what why does this chord exist why Are you solving this problem like this the why is what I want to know the what is clear looking at the code especially if it's written properly right so comment why not what second somebody looked at the piece of code and said my gosh this code is hard to
understand write some comment whoa time out that's another rule I want to follow do not uh comment so do not comment uh on a bad code e instead refactor it so a bad code deserves refactoring it doesn't deserve Commenting and I was working for a for a company out in the Netherlands and I had written a piece of code and as a consultant I keep moving around and I went for another you know opportunity I came back about three weeks later and the team leader said hey thank God I need to show you some code
that I worked on and I said yeah what is it and he opens a source code and shows me I was looking at this code and this code was doing a few lines of code then it had a For Loop and then had an if statement inside of that and I read this it took me about 10 minutes to learn the code once I understood what the code was doing I went above the for Loop and I say slash slash this for Loop does this and I wrote a comment and I'm like okay and then
he said as soon as I wrote that comment because I couldn't understand that code I remembered you really don't like comments you say that in your book I read your book you say don't write Comments like this so guess what I did I turned that comment into a function name and I call that function right there and took this code and moved into the new function what do you think and I said I love this for two reasons he said really what are the two reasons the first reason is it absolutely blows my mind I'm
happy that somebody actually read my book and the second thing I'm really happy for is do you know who wrote the code you just refactored now I don't Know who wrote this code I saw this and I refactored it I said who wrote the code he said oh my gosh I wouldn't have told this to you had I known you wrote this code I said no that's a whole point right we have to keep improving on what we find I'm not going to be perfect in writing the code but you did the right thing is
to refactor it rather than writing a comment on it so that is something we need to do is to continuously improve the code we are Writing that that's very important so make the code self-documented and write executable comments a good test is worth a thousand comments you can write tests are a great way to learn what the code is doing I wrote the very first book I think on Java eight uh Java the book was released the day Java 8 was released now you may say how can you place a book when a language is
a version is released on the same day are you that fast in typing right no I started writing the Book two years before Java 8 was released and guess what was not there two years before Java 8 was released there was no Java dock for streams API and all that and I'm honestly every day I would go get the worst through the Version Control I would download the source code and I read their unit test I learned Java Java 8 functional programming by reading their unit test because that was my guiding force it's a form
of documentation so you can rely on Good tests as a form of documentation self-documenting self-expressive code can be really useful the seventh principle is make sense in seconds you want the code to be immediately clear when you read it it's got to be intentional it is not just the size it is about conveying the intent very explicitly that's extremely important so when you look at oh by the way programmers are very polite people but you have to really hear what they say You probably have heard somebody say this right they say this let me figure
out what this code is doing have you ever heard people say that those words what are they saying they are simply saying this code sucks right because why do you have to figure out what is doing it should be evident when you look at it right it's not like I call this software archeology right you're looking wonder what this is doing I and everybody expresses opinion I wonder what they Wrote back in time right this is like walking through a cave what does this mean that no no I don't think it means it because there
they did something similar but it meant something man these people are thinking there's consistency in the code right what a concept but that's the problem is that we don't know what the code is doing it becomes software archeology at that point so no you don't want to figure out what the code is doing make it absolutely clear What the code is doing make it intentional so here's an example if you will if I ask you what this code is doing you you have to let's think about this for a minute right so here is a
yardstick I would use to see so do not uh make the reader you know a reader read through every single line of code to understand what the code code is doing so in other the words when you look at this code what just happened what is it doing oh Let me figure it out ah this is a for Loop in the for Loop I'm doing an F or in this I'm using this oh I see what you're doing now well you told me to know what it is doing I have to read every single line
of code that is a punishment for anybody reading this code right what you want to do is do you want to convey this really well so look at the code in the bottom right now what does it say far string if is file if file is invalid what is is if file is Invalid say if the file is valid or not hey what does valid mean maybe that I know that from the domain how do you know it's valid simple answer I don't care and that is a very important what is what does I don't
care mean in programming words what was that come on say it louder abstraction and one more the e word Bingo right that's the we've been told This a thousand times what do we do when we write code that's for others abstraction and encapsulation what does that mean I abstracted it out what does this code say if it's valid how do you know it's valid I don't care that's encapsulation that's none of my business if you want to know it go over there and find it right so you but what is the benefit of the code
in the bottom not that it's perfect but it tells you what without forcing you to look at every Single detail of the how so in other words you want to so convey the what and delegate the how convey the what delegate the how hey what are you doing here you go how are you doing it over there not my business right so have you worked with people who write long functions raise your hand if you have okay do you believe long functions are a good idea venkat I love long Functions I go every day and
make me functions longer raise your hand if you do anybody no have you seen long functions at work around keep your hands up and look around right that's called cognitive dissonance right I got a good news for you and I got a bad news for you the good news you didn't write those functions I mean you just told me a few minutes ago right bad news the people who wrote Those long functions are at work right now to make those functions longer right so communication you go to work on Monday don't say a word to
sit down and work on your colleague you know who I'm talking about right know who writes long functions comes to you and says hey how was your weekend you could tell this to your colleague Right my weekend was great on Saturday I went to the park Sunday I went to the movie that's it but don't say it you say oh my weekend at seven o'clock on Saturday I took the car out of the garage drove for two kilometers took a rest turn two for three kilometers look at the right turn go for about two kilometers
started raining it was cloudy I can even smell the soil and that's when I noticed that the road got slippery so I had to make a U-turn and I Came back this way and took a left turn keep going like this for a while as much as you can keep going right at some point your colleague says excuse me have you gone mad and you say no I thought I'll tell you how my weekend was like the way you write code right that's not the way we communicate right what do we do we communicate in
knowledge chunks how's your weekend great on Saturday went to the movie uh On Saturday I went to the park Sunday went to the movie really which park did you go to cat the movie right oh the park the one by the main street oh yeah I've heard about it is a family friendly oh yeah I took all the kids they had a great time what kind of activities did they have notice what we are doing we didn't give them all the details right what is that called it's called slap no not physically It stands for
single level of abstraction so principle we use the compose method pattern so instructions are at a single level of abstraction or detail so this is how we communicate hey how was your weekend went to the park on Saturday went to this movie on Sunday that slap that's compost method did I Tell you which Park literally how I went there did I tell you that I took a train or a bus they tell you what time I went no that's the level of abstraction level of detail did they tell you what movie I went to where
I went to who the actor was no went to a movie that's the level of abstraction dive into the next level delegate down right so that is the key so tell me what delegate the how focused on a single Level of abstraction that we can focus on so eighth principle avoid primitive Obsession primitive obsession is where we feel like we are right to write the code at the lowest level possible use libraries use methods that you can rely upon to build on your code rather than being at that low level of detail so here's an
example is spelling correct ironically that function name itself is not spelled correctly Look at the code what is it doing everything is it mixing the what and the how absolutely right and and besides it what does the function tell you it tells you I need to do everything I am the one who's going to tell you how to do it let's rethink about it what if I do this he's spelling correct says I'm going to just get the file and see if the word is contained in it and maybe I can work with that particular
abstraction so the Point is you want to rely upon and delegate to functions to do the job check in frequently and take small steps how often do I commit code comment code as soon as a test passes let's be very honest about it have you ever done this you have a code you start changing it you're making some changes you change this file change that file change that file change that file and then you're like I don't like this idea I don't like This design so I need to undo the change but I've made a
few other changes so I'm going to undo this one change I'm going to make have you ever opened files change it put it back undo undo 10 minutes later did I forget one more filing has it ever happened yeah we all have done that right but here's the key thing one of the key reasons why you want to comment Frequently is the following commit frequently so you can reduce the cost of undo to near zero that's one of the biggest reasons it liberates you so you can innovate you commit at the code I don't have
it with me it's safe oh I change it oh you know what I don't like it blow it away get a copy from the Version Control and off you more off you move forward the cost of undo is near zero you don't fear making change when you Can roll back to the previous state very easily that's the reason for it so you want to commit frequently and take very small steps so check in frequently the tenth principle keep code at one level of abstraction we talked about the compose method pattern so don't try to write
code that you can delegate to another function so it's easier to understand what the code is doing so convey the what like I said is extremely important so is this a refactoring Opportunity should I refactor now so make refactoring a regular activity every day do not do big bang refactoring you want to incrementally refactor your code so when not to refactor sometimes the code is a complete mess you may have to rewrite it if it is it may be too much of an effort to refactor your way to where you want to go but again
consult with others around you to see if this is the right thing to do And so when to refactor refactor before you fix a bug or refactor after you fix a bug don't refactor while you're fixing a bug why is that I'm fixing the bug oh I think that can be better I'm going to modify that function now you mix the two changes into one and you commit it three weeks later they're like we don't want to fix that bug the way you did we're going to roll back the change what did you lose The
refactoring with it don't want to do that right you want the refactor to be separate from the bug fixing separate from enhancements you make so you want to be able to refactor before you change enhance a feature or after you do never in the middle don't refactor in the middle of another refactoring be purposeful what are you refactoring I'm refactoring this database access class then why are you messing with that one right there that's Not related keep that refactoring separate so keep those refactoring things separate as separate comets so when it comes to this we
talked about when How do you refactor take very small steps device a sequence of steps you can take to refactor be continuous not episodic they're taking these small steps be graceful in what you do aim for bite size useful improvements here's a good step to do great that Works Comet here's a next step to take good that works test pass comment take this incremental step to refactor never refactor code that's not in a Version Control so what that means is I just finished refactoring the test is working I'm going to do the next refactoring is
the change in Version Control not yet then don't refactor commit that and refactor because you want to reduce the cost of change to zero right it gives the power To try ideas don't hesitate to throw out change I was on a 16-hour flight when I got into the flight I said to myself I'm going to write a feature and I wrote the feature on this long flight and by the end of the flight I finished writing the feature as I was going through immigration I said to myself I hate the code every bit of it
I don't like the design but guess what it works And I checked into the hotel and right there in front of me is my computer I took a deep breath and I said there you go delete it and it was so hard right because your hands are going to delete your mind is like please don't do you spent 16 hours writing this delete it and now it felt so liberating it only took me about four more hours to write It now like why because now I know the problem much better than I started out I
got a better idea on the design and I rewrote it and this is one of the things I always say be willing to delete and check in frequently so what's the flow identify the code you want to refactor Next Step DOT test not really okay right test and isolate If you need to okay now we got some tests what should we do perform a small and yet useful Improvement yeah it works that's a good change does your test pass ensure the tests are passing hey the tests are passing but I'm not done with the refactoring
what should I do yes commit the code because that's a good useful step we took rinse and Repeat right so go to the next step now and continue so that's what I would call as the flow so be purposeful be deliberate be incremental be graceful take control of it so it doesn't take control of you you need to be able to write through this and it's a skill the first few times you do it you find it awkward find it a little hard but the more you do and the more deliberate you are the much
better handle you have on this as well That's all I have hope that was useful [Music]