Twelve Ways to Make Code Suck Less by Venkat Subramaniam

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right welcome to the session on 12 ways to make code suck less my name is Venkat Subramanyam I want to talk about some of the ways we can improve code quality code quality is something that's very near and dear to me we all spend a lot of time reading code so what can we do to really make our lives a lot easier so but I'm also a why kind of a guy I always want to ask why so I want to first start with a question why should we really make the code quality better and I think the answer I can think about is that really we are the world where everybody wants to be agile but I want to emphasize that we cannot be agile if our code sucks as simple as that when you're sitting down in a meeting somebody is suggesting that they want to make an enhancements or a change to a particular part of the system and then you realize wait a minute they're talking about this XYZ module and the last time I touched that I could not go home for the weekend you're going to convince them this is not a good change to make so it's incredibly difficult to be agile if the code we are writing really is or for quality so if you want to really maintain sustainable development we have to really aim for good quality of code but then of course how do you tell that the code is you know good quality well the code we write actually has a deep meaning code is how we tell our colleagues how we feel about them so when you're looking at a piece of code that's what they have left behind for you to read and and how do they feel about you when they write the code do they do they say we love you when they write the code or do they hate you when they write the code so the code that you're reading you know usually tells you that and that's one of the reasons why it's important for us to really focus on good quality of code that we are writing that becomes very critical I mean it turns out that lowering quality of code really lengthens the development time that's the first law of programming so if you want to really go slow create poor quality code and that slows you down naturally so it's important for us to really focus on good quality code for that reason but how do you really say a code is of good quality how do you measure it well it's really qualitative but one measure I would use is the following the quality of code is inversely proportional to their effort it takes to understand it so if I'm spending more time on a piece of code that usually is poor quality if I'm spending a lot less time getting it and moving on from the code then usually I would argue that it's actually a better quality code so I want to be spending as little time as possible to grasp and understand a piece of code that becomes extremely critical so I want to talk about twelve ways in which we can improve the quality of code we are writing so let's start with a countdown the first way to improve the quality of code is to really tackle the technical debt now I work with a lot of different teams around the world so when I go to a team I always look around and see if they have identified their technical debt and you'd be surprised how many teams don't have a clue what their real technical debt is you know if you're trying to help somebody well the term technical debt was coined by Ward Cunningham and and he coined this as part of his work in the financial industry and technical debt has a lot of relationship to you know like how financial debt is if you if you have somebody a friend maybe or a family member who has financial problems what do you normally do the first question you ask them is what's your debt if they don't even have a clue what their debt is that's even more trouble and then once identify what their debt is what do you do you list the debts down and then you take the highest paying interest one and work your way down well it's exactly on software projects I would like to know do you know what your technical debts are and if we don't know what our technical debt is we have to identify that now if you don't really solve financial debt what happens well I charge amount of money the credit card company sends me a bill at the end of the month saying I only need to pay a minimum balance this sounds interesting so I send a minimum amount and I keep charging at the end of the year I've exceeded my credit limit so what does the bank do they send me a letter saying of you know exceeded my credit limit but then the bank says you're an important customer so they increase my credit limit well the reason is the bank never wants me to get into trouble they want begin to real trouble so I keep charging and at some point the Mario is more than a yearly salary so what do I do now well I got a declare financial bankruptcy or maybe I should change my name grow beard and move to end of the state just for the sake of records that's not the reason I left Texas so the point really is we simply cannot really handle this kind of a situation and we get into financial crisis well a lot of projects do this they get into a technical bankruptcy and where nobody ever once touch the code you probably have seen these projects everybody is leaving and nobody wants to be hired on this project and that becomes really hard to maintain code after that so we need to really understand what the you know technical debt is so what our technical debt oh that schema we haven't really upgraded for a while it kind of bent out of shape we need to revisit it oh those methods that's been deprecated for a while but we haven't time had time to really upgrade those methods to non deprecated methods and a lot of these things this library has been really not performing we don't have time really to go fix it but what is not a technical debt lowering quality intentionally is not a technical debt we got to be very careful about it that's called sabotage so we have to really focus on handling the proper technical debt along the way and we got to pay it accordingly but what causes technical debt well a lot of times our work schedule pressure causes technical debt and that's one of the reasons I want to emphasize when you're in a sprint planning don't commit all your time to do actual work on the project for new development and fixing bugs schedule some time for paying the technical debt it is not an all-or-nothing you can't say I can't pin everything so I'm not going to pay nothing doesn't really help so what you really want to do is you want to schedule a time so you schedule certain amount of time for development but you also schedule time for other activities like planning for example and of course there's time for you know taking vacations or people falling sick but you also have to take some time for paying the technical debt that becomes very important so one of the things I say on projects is every sprint ask your organization do you know first of all what your technical debt is and second what are you going to do about it can we schedule maybe 10% maybe 15% of the time where we were not we're not going to be doing work on developing new code or fixing those bugs but just revisiting and you know reworking some of these technical debt and clearing them along the way and and unless we take a very active role in scheduling time for it it's not going to go away but not only to be one scheduled time to pay attack of the dead there is another very important thing we need to really keep in mind a person I really admire a lot is Linda rising and she wrote really good books and one of the things she told one's really stuck to me she said a freeway which is packed with cars is a parking lot and and that is so important to keep in mind if you pack a freeway with cars it turns into a parking lot nothing moves around well that's exactly what you are scheduled is if you schedule every minute of your day to do work you don't have any slack time and if you don't have slack time you will never be able to innovate and that becomes really a problem as individual and as organization it's extremely important to have slack time there's a lesson I have taken to heart myself I'm trying to really reduce what I do and have some free time so I can just take a breather and think about you know other things I can do and improve what I do also so one of the books I really like a lot is this book called Guns Germs and Steel and in this book he talks about the history of civilization and it's very fascinating when you read this he talks about how people were savages there are some people still savages but mostly we have civilized and and he says when people were savages they had to get up in the morning and they had to go hunt for food and when you have to get everyday you got to get up and hunt for food and if you don't hunt for food you starve so you have to always be on the run hunting for food and then he says people figured out they could do agriculture you could grow things and I found out they could domesticate animals how cool that is you could entice a little lamb and keep it with you and when you're ready to eat you can just kill it and eat it this is awesome right so once they started doing it they realize I don't have to go hunting today I could take the day off what are you going to do Jonny with the day off let me I can create art I can you know create songs well cultures started developing when people had slack time and that's one of the things we have to really keep in mind as organizations we tend to forget this and we just put people to work to death and that really does not help us at all in getting better at what we do so we have to really start putting those slack times in and also schedule times to pay a technical debt also that becomes extremely well the second thing I want to talk about here is to maintain code with high cohesion so what is cohesion cohesion is where like things are together and unlike things are apart so you don't want to put code where everything is mixed up you know you don't want to put code where let me ask the question and raise your hand if you think putting business logic in the GUI is a good idea not a single person raise the hand let me ask you a different question raise your hand if you see business logic in the GUI right so notice the hands going up this called cognitive dissonance right I know nobody here is doing it somebody else is doing it but the point really is that's really a bad idea that's lack of cohesion but the question is why why should we not really put things together well the reason really is that it really reduces the frequency of change you are going to change the software there's absolutely you cannot save a software from being you know changed if somebody comes to you and says I wrote the software but never changed it what they are telling you is that project got cancelled if anybody is working on any relevant project we have to change it but you don't want to change the software by changing every piece of code that's very expensive so you want to release the next version the change by minimizing the change through a cohesive application reduces as change we have to do that's one of the reasons we want to really reduce co2 increase cohesion so cohesion is where like things are together and unlike things are apart and you want to really keep like things together and that's why we modular rice things we ask you know what is it really this code is doing and anything that's not relevant to it move it away into another piece of code this also reflects back on cyclomatic complexity of code as well longer methods really are not very cohesive and caused a lot of problems for example well in addition to cohesion we also want to keep an eye on coupling what often times we will talk about lowering coupling well you cannot eliminate coupling all the time but you want to be able to minimize the coupling as much as you can but you want to do loose coupling where it's possible well tight coupling makes extending code really really hard so you want to reduce coupling as much as you can but I'm actually a bigger fan of not just reducing coupling but actually eliminating coupling where we can remain we have an experience I was in a conference where it was open space conference and people were talking about how do you know they really like testing but they find mock optics to be unbearable and as I was listening to them after a few minutes of listening to them I blurted out saying hey folks maybe you're having really hard time testing your software maybe because your design sucks and by saying that I made everyone in the room angry and they all hope it means and who are you why would you tell us our designers you know is bad well I said I create a lot of bad design I thought you guys are like me well we then started talking about why mocking becomes an issue and then we quickly realize the problem in this case is that we have dependencies that we have taken in phase value we've a seal that these dependencies are there and they are going to stay and a lot of times these are accidental dependencies so here is an example the code are on the on the very far left is using the code on the middle and the code on the middle is using the one on the right side but the one on the right side is very non predictable it's kind of like maybe a code that tells us what the weather is now this course is a really big problem because the code in the middle is really hard to test it's also really hard to extend as well well but if you're going to write a test on it every single test may have to mark out the code on the right side if people do this they get through this wonderful world I call as mocking hell and mocking hell is not a very nice place to be and after all and and it becomes really painful to write code and write tests but this is where I suggest that we should eliminate dependency so what I want to do is I want to move the dependency are eliminated from the middle code and move it up to the one on the left now when I do this the beauty of this is I can pass a piece of data to the code on the right and then that can use the code I have to do almost no marking for this code well that code which was doing quite a bit of complex work now becomes a lot easier to test it doesn't have this dependency well sure enough the code on the left now took on a dependency that it did not have before but the beauty of this is it requires actually a lot less testing than the other pieces of code did and so we can actually reduce the burden on ourselves in these cases so by eliminating or at least moving away dependencies we can save quite a bit of effort I apply this technique quite often when I write code and this generally actually makes a lot easier and reduce the mocking also that we would need well the next thing I want emphasize here is when we write code we want to program with intention you know I'm sure you have a senior share right you're staring at a piece of code and you're not sure why that code actually works and you're looking at it like this is not supposed to work but it works and you're scratching your head and you're not sure why and it's very frustrating and somebody suggest you to make a little change and it works and now it's even more frustrating when it doesn't work in the first place these kinds of code are very very tricky so how can we really get better at it Weiss came across this particular phrase that just sums it up it said well when I wrote this code only God and I understood what I was doing now god only knows we all have this feeling sometimes right you look at this code and you start complaining endlessly about this code sometimes you complain so much about a code right and then you realize scrolling up it's your name on the top it doesn't feel that bad anymore right and you think yourselves it's got any reason I wrote this very frustrating when you come across code like this it can be really hard to maintain over time so I'm a huge fan of this rule called a Kent Beck's rule of simple design and he emphasizes four simple rules to create better quality code he says that code has to pass all tests the very first statement has an implicit assumption there that we actually have tests so the code passes all tests but the second thing he talks about is the code reveals its intentions and that is very important emphasis the code should be really expressive it should be easy to see through what we call as a transparent code versus a opaque code and then he says that it should reveal its intentions to be obvious what it's trying to do should have no duplications and should be very minimalistic I'm a huge fan of this last point about minimalistic code minimalistic design and I got maybe sometimes overboard in keeping keeping things really minimum because I don't want to really get into a lot of messy code the less code I have the fewer bugs I have the less code I have the less I have to maintain when I have to make a change to the code so in a lot of different ways it can really help us a great deal but one of the best ways I figured out the right code with intention is to write a test before writing the code because we're writing the test you can sit there and think about what should this code do before you actually sit down to write the code so it forces you to not only think about the code you're going to write but also how somebody would be using this code and that can help us to really put the intentions into place so I normally like to write tests before I write code just to bring that out a lot lot better so we talked about a few principles making it really highly cohesive lowering coupling programming with intention scheduling time to lower technical debt but one of the problems we all face as programmers is this thing called primitive obsession primitive obsession is where we feel we have to write the code at the lowest level possible I was removing the code last week and I had about ten lines of code I'm not kidding ten lines of code I'm reading this code back and forth trying to figure out what this code is doing and after a few minutes of reading through it it dawned on me this code is doing something that's already in the JDK so I comment the code out made one call to a JDK function and all the tests are still passing I quietly checked in the code didn't say a word for the programmer to discover this and remove it we do this sometimes we step into a code and thrill I think about this and say I've got to write this code and then you spend all the time writing it and you feel really accomplished that's a very hard day at work and then you realize all that is already done we just waste your time doing this but there are other places where this gets very tricky also so I'm going to say imperative code is packed with accidental complexity this is one of the saddest part most of us have been programming with imperative style code for about 20 years or more which means we have been programming with something which is inherently more complex the functional code is very unfamiliar to most of us but it turns out it's a lot simpler it removes accidental complexity to illustrate the point I want to take a little example and I want to play with it right here so let's take a look at an example here I've got it'll function call the East Prime don't worry about what it does it tells you it's Prime and I have a function a little variable n which is 101 K which is 51 but here's what I want to do find the total of the square root of the first K prime numbers starting with n so how do I do this well I'll first say int index equals 2n and I'll say count is equal to 0 things are going really well so double total equal to 0 notice how we wasted our effort creating variables and doing no real work these are called garbage variables we create variables like this all the time but if you create garbage variables many time what do you do you get angry so what do you do you don't call it index you call it I you don't call it count you call it C you don't call it totally call it T because you are telling those variables you don't deserve to exist and then that's how we express our intent right so in this case of course what am I going to do while count is less than zero stop is it less than or less than or equal to do you ever ask the question every single day and the day you don't ask is called the national off by one error day and that's really annoying and then what do you do then you say if and then is prime of index now that you have four were able to get a stop and think which one and then what do you do well if it's a prime number total plus equal to math dot square root of index and then finally when you're done with this I'm going to output or return even better the total is this code right no what am I missing increment the index okay let me increment the index so index plus plus is that good are we done what am I missing increment account okay count plus plus it's the correct what is the problem do it outside isn't that beautiful you got to think about this do I put it here do I put this here is this correct what is wrong what about K so this should be is less than K is this correct now this did you just notice you all went from saying no to quietness this is one thing I've noticed programmers are the smartest people on earth try this at work on Monday go to a developer and say is this code correct they will never say yes they'll say it looks good because when you find that it is broken that's it only looked good I didn't say yes so let's go ahead and run this it looks good right so you run the code and it produced wrong answer after all this Wow this loses faith in humanity isn't it so that is obviously wrong I made a mistake right you know it could be still working on this code trying to find out why it doesn't work but I got something for you how does this code make you feel really stupid isn't it in fact I have a theory it's code like this that prematurely makes programmers into managers right you're like I'm done you clown sit there and work on this I'm done right this is an example where it gets really bad we don't want to do that so what can we do differently maybe we can try this maybe there is hope for us so what I'm going to do is retry this and I'm going to say stream well return of course stream dart iterator well what am I going to start n E + E + 1 hey what in the world is that that's an infinite stream Wow how long is the infinite stream duh it's infinite well if it's infinite where do you store it on the cloud of course okay so then what do we do I want to say filter sample in this case of course and I'm going to say this is YZ Prime great then what do I want to do I want to map and I'm going to say mat Squire root are we done well you got to say limit limit what K is it less than K its K damn it move on right and then of course I'm going to say summit and total it and return it well let's see what this code is going to do well in this case of course I got to have the stream coming ends so stream data rate so I have a stream iterate iterate not the iterator okay so go ahead and run that code and you can see that's the answer not ten so you can see how that code ended up being a lot better than what we tried so unfortunately when we write code that is really unmanageable we normally suffer the consequences of the code that's what we end up doing but thankfully by writing code that is easier to understand easier to work with if you look at the code the imperative style code if you're showing this code to a colleague or a business analyst you're sitting and trying to debug this code your business analyst says hey what does this code do and you said that's what I'm trying to figure out be quiet and this becomes very frustrating but code like this you can actually talk to them you can say this is what we do step one step two step three test step four does it make sense you do a single pass through this through this code it's easier to understand as you can see so a good code should really read like a story not like a puzzle so when you write a piece of code that looks like a puzzle what happens everybody is scratching their head trying to figure out in the meantime we have production code to release but I want a code to be like a story you just read it it's like oh that was interesting got it right you don't want to have puzzles in the code it should be really easy to understand it well the beauty of this is we get excited about functional programming but the real power here is declaration style of programming so on the Left I have imperative style on the right I have decorated style but it turns out every piece of functional style code is actually declaration so what is imperative style code imperative style code is where you have to say the same thing over and over and over this is like talking to a toddler the further you talk to a toddler it's exciting the next day you talk to the toddler you realize you have to say the same thing the third day you got to repeat the same thing again walk slowly please don't step on the cat hold it with both hands and then you realize this is going to go on for the next 18 years this is called parenting right the decorated code on the other hand you tell what to do but you don't focus on how to do it so that becomes a lot easier to work with it but it turns out functional style code actually is declarative plus higher order functions so it's the Dec limited nature of functional style that really gives us the advantage and so that's one of the reasons why we want to favor that thankfully most of the languages today support that including Java of course so we can start using it the next one I want to talk about is to avoid clever code and to use clear code now we all have taken taken time to write clever code haven't we why do we write clever code because it feels good and when you create a clever code your proverbial hand comes and Pat's you in the back right it's like you are awesome well I remember this experience I can never forget it I got an email saying something is really off can you fix it and I looked at the problem I would have fixed it in five minutes I could have fix it in five minutes but I said to myself why would I want to fix this problem I want to fix the mother of all problems and so I spent an hour coding this honestly when I finished coding it I had an out-of-body experience I saw venket get up and Pat me in the back and hug me and say you are the most awesome right and it felt really good about you know a couple of weeks went by I got this email from the client saying something really terrible has happened in production I looked at it immediately replied saying don't worry I can take care of it in the next few minutes they said we know you can't you can take care of it you are good I replied back saying no I can take care of it not because I'm good I can take care of because I cost it and I remember this and what did I do I undid my code and put the five minutes solution it's been seven years now no problems at all so these days when I'm writing code a thought comes to me that this is clever I delete the code immediately and I start over I don't want to write clever code anymore I want to write clever a clear code so that's something we have to really work hard to create code that is actually easier to understand well here's one of the codes I really like a lot programs must be written for people to read and only incidentally for machines to execute there is something we have to really strive hard because code is written ones but it's rewritten several times code is being read several times so it is our responsibility our responsibility to really make the code readable that becomes extremely important otherwise we are going to be really causing more expense for the organization I'm going to say 10% of the time we right ugly coat for performance reasons the other 90% we write ugly code just to be consistent with the other pieces of code so we don't feel guilty about it and and so as a result the entire code becomes really hard to maintain over time and those who sacrifice quality to get better performance may actually end up getting neither and this becomes very evident because when we do realize we have to improve the code the code is completely beyond repair and and we need a team of people to look at it and we really fail at it so another code I really like there are two ways of constructing a software design one way is to make it so simple that there are obviously no deficiencies and the other is to make it so complicated there are no obvious deficiencies we see this all the time because we don't even know how the code is broken I remember working with the client I was looking at this complex code and suddenly I yelled out saying oh wait I just found a concurrency issue in this code here is a variable totally unprotected multiple threads could be accessing it and when I said this one of the difference got very angry and the developer said hey Venkat this code has been in production for three years what makes you think you can come and scare us today I didn't know what to say but thankfully I didn't have to because before I could answer one of the other developers said aha but wait a minute the code crashes every three weeks and we don't know why so we don't even know why it's failing and we've been spending a lot of time debugging so that happens quite often as well well the next one came actually from a totally surprising you know place it is a book that I've read before and I really like this book a lot it's a very old book but it's a timeless book this is book by William Zinser on writing well and he talks about how to write nonfiction and in writing nonfiction he outlines four principles for writing better English as I was reading this book I realize it's not about writing English alone it directly applies to writing code I realized and I liked this book so much that I've started gifting this to a lot of people these days because it's it's that good but a four principle he talks about are the first one is simplicity so what makes code really you know not simple or complex want to say moving parts make code really complex if you have a lot of mutability encode it becomes really complex so keeping the moving parts fewer and an avoiding mutability can help us really make the code simple it also solving only the real problem we understand and not solving mother of all problems can help us keep the code simple as well the next thing he talks about is clarity he says what you write should be clear that's true for code as well what makes code really hard to understand well a lot of times the code is hard to understand when the code is not cohesive when the court has too many things going on it becomes really hard to understand it long functions are hard to understand a curve is not clear when the flow is not really good at all you're trying to read the code and saying what are we doing here why are we changing this suddenly why are we changing this it becomes really hard to understand it he talks about brevity he says shorter you know sentences are better than shorter longer sentences shorter paragraphs better than longer paragraphs short of chapters better than longer chapters and so on well in writing code brevity really comes to keeping the function smaller keeping the class is smaller and cohesive so we can definitely do a lot to address that but put together these things are extremely important that we want to write the code in a way others can understand and when you write code in a way others can understand they can maintain the code more effectively by making it clear one of the other ways to make the code clearer is to give good variable names for example so if you're giving really poor variable names or class names it becomes really hard to understand the last one he mentions is humanity in writing that was the most difficult for me because I looked at her and said humanity we have programmers we don't care about that stuff and I was kind of puzzled by it and it turned out that's one of the most important things because when I go to developers and say how would you program this they give me all kinds of nonsense but if I ask them how would you do this as a human a beautiful lively design comes out of things so I think it's important for us to consider humanity but I know it's as programmers it's really hard the other air was at my optometrist she was looking into my eyes and she asked me what you do for a living I said I'm a programmer and then she talked about it for a few minutes and then she suddenly said what do you living I said I said I'm a programmer and she said I know you said it but I asked you again because you look normal so you know sometimes we feel like this right you're not supposed to be you know like you are you should be weird and and that's one of the things we really put Humanity as the last that becomes really hard for us oh this is one is really near and dear to me I refuse to allow comments in my code I do a lot of code reviews and when I do code reviews this is one of the biggest complaints I have about people I don't like to see comments at all the reason is I like to see comments that tell me why not comments that tell us what I'm sure you've seen you our share of really bad comments the other day I was looking at a piece of code it said I plus plus and they were very helpful they said increment I'm like thank you very much as not you're as I'm getting older I can see these symbols like so you know that's really helpful or you know comments that even even worse you got a little variable X and then they do this and then there's a beautiful comment that says shift but I don't know why you shift it I can see that you shifted it so this can be extremely painful when we write code so it's important for us to read think about commenting in general so don't comment to cover a bad code so a month of the opinion that people write comments to cover a bad code so if somebody tells me this code is hard to understand commented I'm like timeout this code is hard to understand refactor it so that is something we have to really take the time to make the code readable and understandable and we want to write code that is expressive and self documenting so in my opinion when it comes to code I want to really the code to be self documenting expressive it's easier to see easier to understand so to me a good code is like a good joke when was the last time you set a joke and people didn't get it the worst thing you ever do when you tell a joke and people don't get it you start explaining it it doesn't go well at all because you explain it and then they look at you is like uh-huh is it funny why let me explain to you again it's going to be a very long evening there's only one right thing to do when you say a joke and people don't got it get it you say a joke people kind of stare at you and you say never mind don't bother pretend like I never said that and then you go home sit in a corner think about it and you refactor your joke and then the next day you come and try it with the new group of people and see how it goes and you do it iteratively improve your jokes so the point really is a good joke it could good code is like a good joke writing comment is like explaining a joke it never goes well so when I look at a piece of code I want to know what the code is doing what the code is saying I don't want a stinking comment to come in and tell me you know what the code is doing I want the code to be really expressive this really becomes a problem we live in a world where we are absolutely infatuated with this and we make things really worse I was in Washington DC and I wanted to take a shower so I got into the shower I should be showering but I couldn't I had to tweet now because I saw this and I got very angry because the shower had a documentation on it it says put to turn on it's what the heck why would I need to be told how to use a shower so immediately I have to tweet it those who cannot design are condemned to document and we see this all the time and this becomes incredibly difficult our API is begin to stink it becomes expensive people sit there and say it takes three arguments but I don't know which order I should pass them why because arguments are in p1 in p2 in p3 right so I don't know what which is which and we waste time trying to figure this out it becomes expensive over time well here's an order three what is three I don't know will document it well order three large coffee well or maybe we can say order coffee size start large maybe that's a little bit better the code becomes more expressive so we can think about creating code in a way it's more expressive so we don't have to be really writing comments as much as we do so document code using well chosen meaningful names your names become documentation use comments to describe the purpose of the code and the constraints don't abuse comments to substitute for good code there is something we should really try to do we should definitely avoid long methods long methods are painful when we use long methods it becomes really really hard to understand what the code is actually doing there are several problems with long methods long methods are hard to understand long methods are hard to test long methods read to duplication long with its are hard to reuse the other day I was talking to a gentleman and he said very painful he said did you notice long methods become longer it's it's really true right but very sadly true you know I travel a lot so when I go home one of the things I always say is looking at my children I say oh you are taller now that's a good thing but I come back to work and say you are longer now that is not a good thing when you look at the code so that becomes really painful as well and when you have long methods long with its black cohesion long methods you know increased coupling it's a diagonally opposite to good design so good design says high cohesion and low coupling long methods have low cohesion and high coupling so they absolutely are on the opposite end of good design it becomes really hard to maintain such code so how long is really long when it turns out this is really a wrong question to ask because different programming languages have different nature in how we express code what may be long in one language may not be long in another language and and the number of lines of code is really not a yardstick so it turns out that the length of the long method it really is not about the length of the code but it's a level of abstraction in the code so when we look at a method we should ask how many levels of abstraction are you dealing with in this code and we want to really focus on the so called single level of abstraction and if a code has a single level of abstraction that becomes easier to understand easier to maintain if a code has several levels of abstraction it becomes really hard to understand so one of the things to look at is not the length of the code but the width of the code if the code has several levels of indentation well it's even worse if they're only intended but assume they indent it well that means that it really becomes like a mountain if you look at it on the side and that can be a problem because to grasp this particular thing you got load up so much in your memory so imagine you are reading a piece of code and what are you doing you have to read the code and then you're like okay I got this and you're reading more and you got this and you're reading more and at some point you realize I can't hold all this in my head if you want to think about what it feels to read long methods I'll tell you how it feels you take somebody and you don't them in water and hold them down after five minutes you let them up and then go in that's how it feels reading long methods isn't it because I'm trying to load them all in your mind you can't just keep up with it so we have to be really considerate for other people who have to read our code that becomes extremely important one of the things that we can do to improve quality of code and I say this really vexing because I see this with almost every single developer at various degrees of experience I work with a lot of clients I work on projects so I have to go meet strangers and work with them and and one of the things I get to do as this is to pair up with them and when I sit with them I will take note of how they give their variable names and the variable names are absolutely random it is kind of like the cat walked on their keyboard to give the variable names and he like and the other day I was looking at a piece of code and I did not continue reading the code because now I was trying to find out a pattern in the variable names they were selecting I wanted to see what the next variable name would be it's okay I'm gonna Z and a P and a W what would next one be so now we are curious to find out this algorithm if there was one that they were using to find the variable names this is really hard I was teaching a course in in Virginia and I was telling this team they should never use single letter variable names other than a few exceptions one of the developers came to me and said hey we're a fortune 500 company we have biggest software company in the world and you think you have to come and advise us about writing quality code and not using cumulative variable names is that I do it I didn't mean to offend you if you're doing that great you know awesome just ignore my comment we want is our office just pulling your leg you should come and look at our code it's a disaster everything is a single letter variables so and then about six months later was back in the company and the same guy came to me and he said do you remember we talked six months ago I said yeah I remember you giving me a hard time he said I want you to know that you made a difference so for a minute I was really proud I said really he said yes we don't use single letters anymore we use only two letters now habits are really hard to kill so finding variable names is extremely hard but one of the reasons is we really have worked with people who are completely ignored us when we did this I'll give you an example of this I was walking on the on the you know in the garden with a guy who was way taller than me it's probably about at least a feet taller than me I was like a chicken walking next to him so we were walking and there was somebody sitting over here the trash can over there and he you know drinks the soft drink or whatever he was drinking and he throws the can right from here the can hits the trash can and then falls right in on the on the ground and the dude who threw it looks at and says yeah lost my aim and then turns on to do something else so the gentleman I was walking with this white helps to really be tall I think he stops and then says hey you do you want to pick it up and put it in the trash can or do you want me to come and pick you up so you can pick it up and put in the trash can and the guy is like yes sir I'll take care of it and then puts it I'm like wow I want to be like him one day and but this is exactly the point you see somebody create a bad variable name you shrug and say okay that's life in the big city but if you say do you want to create a better variable name or do you want my me my help to create a better variable name you are telling developers don't come trash my code we really care about the code we create and we're not going to let you come and put variable names that don't make any sense because when you do it's optimized for writing but it's totally unoptimized for reading and everyone else in the team is wasting their time and money trying to figure out what this code is doing becomes very very frustrating so a programmer is somebody who can name their children very quickly but has a very hard time naming their variables I remember this experience very well my wife came to me and said we want to decide a name for our son well our kid here's the name she's like wow that's it that simple instantaneously a name I said sweetie that's the name for the kid now if you leave me alone I got to think of the variable name now and this is really hard for us right because variable names are extremely difficult naming children no problem at all I can name them more right and the point really is it's incredibly difficult to give us give give variable names I was working on a project for a client and I was doing code reviews for them and I was just sitting and pairing with this gentleman as was doing it and he just browsed through a piece of code I said oh wait a minute back up and then he backs up I said would you mind if I take a little photo of this is I'll go right ahead it's a very expensive product and the people working on this chord are very expert developers by the way and I took a photo and he may say what's funny about this code did you take a photo well what I took a photo of was this code why reason I did code was what was right below this it said God helped me I have no idea what this means and and this you know and I'm going to look at code like this I have a feeling you are an expedition you you know you come down through this cave and come to the bottom of the cave and on the wall there's a huge written block says help and then look down there's bones below that's what we feel about it right these developers these are the last words help and then they just died away right I'll quit one of the two so these are really hard to maintain this becomes extremely hard over time so we have to really think of variable names variable names represent abstractions I don't want to give poor quality variable names I'm okay with eye for an index variable in a loop that's okay but in any other case I want to give names that actually read tells me what it really means it takes I know this is a habit and a lot of us have this habit of just clicking on some keys one or two letters but if we just spend a few minutes thinking about the variable names it becomes habitual the good habits become the habit rather than the bad habits become the habit so if you cannot name a variable or a function appropriately it may me it may be a sign that we haven't really understood the true purpose of this variable or function so this usually is a reflection of us not taking the time to understand deeply what this means and we have just rushed through it at this point and that can become really really hard to maintain so passing and asking that question and and this is one of the things I know Kent Beck talked about programming with intention when I write a test and when I write the code one of the things I emphasize is when you write a test the first few tests are there to piece out the interface of my class or interface of my function so I would return silly things from this function I would return to true or our fake result and people would look at this and say that's silly why are you writing a test and not and giving us stupid implementation well they're missing the point the reason we do this is we take the first few tests to really piece out the functions he is the function name really good or should I change the function name I don't have to rush to implement the body of the code right now let me keep my eyes on the name of the function let me think of the parameter types let me think of the parameter names let me think of the return type let me just focus on what this function should do and how it feels for somebody to use it before I come in and start putting the body of the code and that is the real purpose of writing these tests if we're not passing when we are writing these tests if we use these tests as a mechanical process of just writing something and moving on then the tests have not really helped us to improve their design of the code that becomes extremely important for us to use so it's important to give really good variable names the next thing I want to emphasize here is to give it is to do tactical code reviews I cannot emphasize the need for code reviews I started doing code reviews as a young programmer I have this is probably one practice I can tell you that I've followed ever since I not be in a year when I have not practiced code review on a project and of course when I say do code reviews people get read the anxious a lot of times for example Joseph says oh wait a minute you guys are going to get together on Thursday afternoon put my coat on the big screen and then talk bad about me oh no I'm gonna call him sick I'm not going to come to work Sarah in the meantime says oh wait a minute I'm already behind schedule I don't want to waste my time looking at the stinking coat that Joseph wrote never mind I'm not coming for that in the meantime the manager comes to you and says wait wait wait did I hear the word code review oh yeah we're going to do this on Thursday the managers heck no because the last time you guys got together and did a code review there was a fight we had to call the cops and two people quit no more code review for you right so code reviews are very politically charged and nobody likes them and so as a result we all shy away from doing it well I've been code review for a few decades now and if you ask me this is probably one of the practices that I really really like a lot and the reason is when we do code reviews we are removing so many errors by proactively reviewing them so when I do code reviews I don't not only review code I actually review the tests as well that's one way to make sure that people actually writing tests also in fact I usually review the tests before I review the code itself so we do a very active code review we also do what I call as a tactical code review so what is a tactical code review we don't bring entire team into a room to review well I finished a piece of code and he is going to review it now well the next piece of code I'm writing he is gonna review it maybe the third piece of code I'm going to write he is going to review it so I'm gonna rotate it among the developers and of course while he's reviewing my code his code would be reviewed by another person so every little piece of code and it has to be complete we got somebody else in the team reviewing it I'm also not a big fan of using tools you know if the tools are working for you that's awesome if the tools are not working for you throw them away the tool is not the issue sometimes people tie checking in code to code reviews I think that's a really terrible idea because if you say you cannot check in code if you don't review people don't check in code and and they've delayed checking in code which is not a good thing or even worse they simply approve the code because the chicken can go through once in a while put something absolutely stupid in the code and see if your colleagues are catching it if they say it's good you're in trouble so you want to make sure the code review is actually working a real feedback has to come well people often ask how do you motivate a team to really do code review and I am NOT a big fan of mandating things when they begin to truly feel the benefit of code review they will come and ask you I've seen this happen actually when they come to you and say would you please review my code because it improves what I'm doing I'm learning from it and and it only becomes better and and so a record review has to really be valuable not procedural not administrative and when we make it valuable people will begin to use it also keep in mind you never want to insult people during code reviews your goal is never to say oh this sucks or why can't you be a better programmer these kinds of things are really bad things to say so my recommendation is never say what's wrong in the code always say what can be better so when you say what can be better you are giving an escape route for them to apply something or come up with something even better than what you what you suggested but this gives an opportunity for them to improve rather than being slapped on their face keep in mind that code reviews are both technical and sociological we have to respect the human who is behind the code as well that is extremely important for us so when it comes to this peer reviews can catch 60% of defects and perspective based reviews can be more effective what I mean by that is the person reviewing the code should be another programmer working with you I don't want somebody once used to write the code to come and review the code those are called Priesthood based code review I don't want priests basically code review I want practitioners to be reviewing the code and peer reviews are are complimenting to test cases and we got to keep this aspect of social nets in here so facilitate this code of your tactical code review to improve the last point I want to bring out here is if you ask me there's one thing I've done differently in the past about maybe five to seven years compared to the years before I always look back and say what have they done different in the past few years you know I'm a just doing the same thing I can put my finger on this one I used to create object-oriented code which was bloated a lot of state now when I sit down with developers they sit down and the first thing they do they create private variable I said why are you creating this variable I never want the state to be self-serving I want the state to fall in place to meet the behavior of the code I'm writing so I never start with private fields and getters and setters these days I start with methods write tests for methods write the methods but as I'm writing the methods for a certain behavior certain action I let the fields come in the state to fill in and serve those behavior rather than being self-serving and then this takes a little bit of practice but once we start doing it we can move towards minimalism and I realized that actually I can create code with a lot fewer state than I used to and when I also mentor and work with other developers I often question them why did we introduce the field right now why don't we wait a little bit and see if the field is really needed sometimes it is but a lot of times it's not so we can reduce the state in the code quite extensively doing this so reducing state is something very important so my recommendation is think more typeless aim for minimalism fewer states less mutability and just enough code for the known relevant parts of the program now this requires us to really focus on reducing and keeping things really minimum we tend to write a lot of code very quickly and when we write a lot of code very quickly remember every line of code we write is a liability for us to maintain so I'll be very reluctant in fact I would say this is what experience really is you catch a very young programmer who just graduated from school and at 8:30 in the morning you stand by the door of the office and say where are you going and the programmer all eager says I'm gonna go write code just wait for 15 years and the same person 15 years later catch them at the door and say where are you going I'm going to remove all the code we wrote right this is called experience experience teaches us do not write code that's not needed and you're trying to remove it in fact sometimes you just come to work enough time to remove whatever somebody else wrote right we keep a balance in the in the system and so you know I worked with clients these days and if you ask me what do I do I go to a customer site when I leave they actually have lot less code than they did when I came in said why are we doing all of this get rid of it and we want to really remove this and mutability makes really hard for us to write code as well and we want to reduce it well here's my philosophy messing with state is the root of many problems both in software and in politics lot of countries go to war because of state well that's exactly what happens when we write code I was actually looking at a piece of code the other day and I saw there was enormous amount of mutability in this code and I noticed this mutability and I saw a few bugs in the code as well I just started laughing because the bugs were in the code directly because of this mutability and I didn't tell the developer oh this really is bad don't do this I just kind of politely prodded saying why don't you rewrite this code using this you know map and reduce you don't need this fun you know immutability here well an hour later the developer comes back to me and says you know this is really funny you told me to refactor this code so I did and I was actually shocked because when it removed it a few errors I had in the code just went away and and that is one of the beautiful things about code is when you reduce mutability the error rate goes down as well so I'm going to say immutability needs company it all often hangs around with bugs there there's they always seem together they hang out in the bars all together right and this happens a lot so when you reduce mutability you often have less bugs in code this is one of the reasons I really like the functional style of programming because we're removing all this garbage variables from code and that really eases the pain for us quite often so want to really reduce that mutability as much as we can so we talked about the 12 ways to make the code suck so I want to leave you with some departing thoughts well here's a list of things I talked about so a schedule time to lower technical debt a favour high cohesion and favor loose coupling I also want to emphasize when I talk about loose coupling also reduce coupling as much as you can a program very deliberately programmed within 10 an avoid primitive obsession in code we tend to really write a lot of code at a very low level but if we just step back and see is that a function available already to do this and and think more declarative ly then imperatively that can reduce that burden for us prefer clear code compared to clever code if you feel that a code is really clever rewrite it or ask for help or ask somebody else to read it if you really want to make a code readable there's only one way I know to make a code readable to have somebody read it so take it to somebody and say hey read this code and tell me what you think about it apply the principles of writing to writing code keep the chords simple keep the code clear keep the code brief you know smaller piece of code is better than longer pieces of code and and consider Humanity when writing this code that becomes extremely important you know this is one thing to think about you know I was thinking about code and why code is so hard to read I remember the favorite time I want to really go to graduate school and so I started reading for GRE well this was back in time GRE had three parts to it analytical numr and then you know English and I didn't speak English until I was 17 so English is extremely hard for me and so I looked at this and I'm like wow these English words math was not a problem analytical is not a problem is both of them got almost maximum points and I deliberately failed English because I just could not I looked at all the words in the GRE I'm like my gosh I thought people in America speak English that I would never be able to understand and so I just completely skipped it the universe too kind of took pity in me and said this guy is not really that bad he can do math will hire him even if even if he cannot speak so I went to school and I was blown away by the way because of the 30 years I've lived in the u.s. not a single day anyone came to me I never used a word from the GRE book I can actually understand what they speak I don't have to look at the dictionary every few minutes excuse me hang on just hold the thought I want to see what you're saying I don't have to look in the dictionary and then I realized freaking building a wall the GR exam does it already right makes it so hard for a lot of people to approach we have to really be practical in what we offer to people if people don't have to use those words in the society why ask them to go through schooling to learn words they would never ever use something to think about so comment why and not what it's important for us to focus on self documenting code that is extremely important and once we do the code becomes easier to understand easier to maintain and the comments don't go out of synch with the code after all avoid long methods focus on single level of abstraction and give good meaningful names to variables and do continuous code reviews and minimize state and minimize mutability of state as much as you can so we talked about these about twelve different things but there's a lot of things we can do almost on a daily basis but and one of the things to remember is we simply the fun is not in writing code the effort is not in writing code it is always about rewriting code and that is something we have to really begin to keep in mind because if you look at every single field even if you look at the greatest of artists who have walked this earth they never sat down and did things once every one of them created prototype after prototype after prototype and what they created as masterpiece was not the beginning but a result of a lot of different efforts where they got it so what we need to keep in mind is one of these departing thoughts the first step in becoming a better programmer is to let go of the conviction that we can code it once and get it right the first time because once we really deeply keep that in mind we are never in a rush to write the code we write the code then we rewrite it we evolve it and we then take the pride in actually making the code readable and then we don't count on how fast I can write the code but how fast I can help other people read the code that becomes extremely important and this is something I remember quite often you know when I write books the latest book I wrote this is one thing I had to do I had to throw away completely a chapter for times and rewrite it until the point I started feeling better a better with it even before the editors were able to look at it and but knowing that you really have to rework and rewrite gives you the courage gives you the you know ability to say I don't have to just write this once and walk away I can actually come back and improve my own work and that I think is very noble uh if you want to download this code are the slides it's under in the site I hope you found that useful that's all I have thank you
Info
Channel: Devoxx
Views: 78,987
Rating: undefined out of 5
Keywords: DevoxxBE2016
Id: nVZE53IYi4w
Channel Id: undefined
Length: 60min 44sec (3644 seconds)
Published: Thu Nov 10 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.