YouTubevideo· Aug 16, 2024· 22:23

The Easiest Way to Write Good Code

Watch on YouTube ↗

transcript

51 moments
  1. when you're writing code you're never going to get it right the first time so why not make the mistakes that you need to make in order to write the code that you need to write on this week's episode we're reading an article from te called write code that is easy to delete not easy to extend you can find te on Mastadon te that's TEF te's website is

  2. programming is terrible. comom where you can find about te as well as this article right code that is easy to delete not easy to extend write code that is easy to delete not easy to extend written on February 13th 2016 quote every line of code is written without reason maintained out of weakness and deleted by chance John Paul

  3. starter's programming in Anie C every line of code written comes at a price maintenance to avoid paying for a lot of code we build reuse able software the problem with code reuse is that it gets in the way of changing your mind later on the more consumers of an API you have the more code you must rewrite to introduce changes similarly the more you rely on a third party API the more you suffer when it changes managing how the code fits together or which parts depend

  4. on others is a significant problem in large scale systems and it gets harder as your prodject grows older quote my point today is that if we wish to count lines of code we should not regard them as lines produced but as lines spent ewd 1036 if we see lines of code AS lines spent then when we delete lines of code we are lowering the cost of Maintenance instead of building reusable software we

  5. should try to build disposable software I don't need to tell you to that deleting code is more fun than writing it to write code that's easy to delete repeat yourself to avoid creating dependencies but don't repeat yourself to manage them layer your code to build simpl to use apis out of simpler to implement but clumsy to use Parts split your code isolate the hard to write and the likely to change parts from the rest of the code and each other don't

  6. hardcode every choice and maybe allow changing a few at runtime don't try to do all these things at the same time and maybe don't write so much code in the first place so Step Zero don't write code the number of lines of code doesn't tell us much on its own but the magnitude does 50 500 5,000 10,000 25,000 Etc a million line monolith is going to be more annoying they need 10,000 line one and significantly more

  7. time money and effort to replace although the more code you have the harder it is to get rid of saving one line of code saves absolutely nothing on its own even so the easiest code to delete is the code you avoided writing in the first place step one copypaste code building reusable code is something that's easier to do in hindsight with a couple of examples of use in the code base than foresight of ones you might want later on the plus side you're probably reusing a lot of code already by just using the file

  8. system why worry that much a little redundancy is healthy it's good to copypaste code a couple of times rather than making a library function just to get a handle on how it will be used once you make something a shared API you make it harder to change the code that calls your function will rely on both the intentional and the unintentional behaviors of the implementation behind it the programmers using your function will not rely on what you document but what they observe it's simpler to delete

  9. the code inside a function than it is to delete a function step two don't copy paste code when you've copy and pasted something enough times maybe it's time to pull it up to a function this is the save me from my standard Library stuff the open a config file and give me a hashtable delete this directory this includes functions without any state or functions with a little bit of Global Knowledge like environment variables the stuff that ends up in a file called util

  10. aside make a util director and keep different Utilities in different files a single util file will always grow until it's too big and yet too hard to split apart using a single util file is unhygienic the less specific the code is to your application or project the easier they are to reuse and the less likely to change or be deleted Library code like logging or thirdparty apis file handles or processes other good examples of code you're not going to

  11. delete our lists hash tables and other collections not because they often have very simple interfaces but because they don't grow in scope over time instead of making code easy to delete we are trying to keep the hard to delete Parts as far away as possible from the easy to delete Parts step three write more boiler plate despite writing libraries to avoid copy pasting we often end up writing a lot more code through copy paste to use them

  12. but we give it a different name boilerplate boilerplate is a lot like copy pasting but you change some the code in a different place each time rather than the same bit over and over like with copy paste we are duplicating parts of code to avoid introducing dependencies gain flexibility and pay for it in verbosity libraries that require boiler plate are often stuff like Network protocols wire formats or parsing kits stuff where it's hard to

  13. interweave policy what a program should do and protocol what a program can do together without limiting the options this code is hard to delete it's often a requ re M for talking to another computer or handling different files and the last thing we want to do is litter it with business logic this is not an exercising code reuse we're trying keep the parts that change frequently away from the parts that are relatively static minimizing the dependencies or

  14. responsibilities of Library code even if we have to write boilerplate to use it you are writing more lines of code but you are writing those lines of code in the easy to delete Parts step four don't write boilerplate boilerplate works best when libraries are expected to cater to all tastes but sometimes there's just too much duplication it's time to wrap your flexible library with one that has opinions on policy workflow and State Building simple to use apis is about

  15. turning your boiler plate into a library this isn't as com uncommon as you might think one of the most popular and beloved python HTTP clients requests is a successful example of providing a simpler interface powered by a more verbose to used Library URL lib 3 underneath requests caters to Common workflows when using HTTP and hides many practical details from the user meanwhile URL lib 3 does the pipelining

  16. connection management and does not hide anything from the user it is not so much that we are hiding detail when we wrap one library in another but we are separating concerns requests is about popular HTTP Adventures URL lib 3 is about giving you the tools to Choose Your Own Adventure I'm not advocating you going out and create a protocol and a policy directory but you do want to try and keep your U directory free of business logic and build simpler to use

  17. libraries on top of simpler to implement ones you don't have to finish writing one library to start writing another at top it's often good to wrap thirdparty libraries too even if they aren't protocol esque you can build a library that suits your code rather than lock in your choice across the project building a pleasant to use API and building an extensible API are often at odds with each other this split of concerns allows us to make some users happy without

  18. making things impossible for other users layering is easiest when you start with a good API but writing a good API on top of a bad one is unpleasantly hard good apis are designed with empathy for the programmers who will use it and layering is realizing we can't please everyone at once layering is less about writing code we can delete later but making the hard to delete code Pleasant to use without

  19. contaminating it with business logic step five write a big lump of code you've copy pasted you've refactored you've layered you've composed but the code still has to do something at the end of the day sometimes it's best to just to give up and write a substantial amount of trashy code to hold the rest together business logic is code characterized by a NeverEnding series of edge cases and quick and dirty hacks this is fine I'm okay with this other

  20. styles like game code or founder code are the same thing cutting Corners to save a considerable amount of time the reason sometimes it's easier to delete one big mistake than try to delete 18 smaller interleaved mistakes a lot of programming is exploratory and it's quicker to get it wrong a few times and then iterate than think to get it right the first time this is especially true of more fun or creative Endeavors if you're writing your first game don't write an engine similarly don't write a

  21. web framework before writing an application go and write a mess the first time unless you're psychic you won't know how to split it up monor repos are a similar trade-off you don't you won't know how to split up your code in advance and frankly one large mistake is easier to deploy than 20 tightly coupled ones when you know what code is going to be abandoned soon deleted or easily replaced you can cut a lot of Corners especially if you make one-off client sites event web pages anything where you have a template and stamp out

  22. copies or where you fill in the gaps left by a framework I'm not suggesting you write the same ball of mud 10 times over perfecting your mistakes to quote peist everything should be built top down except the first time you should be trying to make new mistakes each time take new risks and slowly build up through iteration becoming a professional software developer is accumulating a back catalog of regret regrets and mistakes you learn nothing

  23. from success it is not that you know what good code looks like but the scars of bad code are fresh in your mind projects either fail or become Legacy code eventually anyway failure happens more than success it's quick to write 10 Big Balls of mud and see where it gets you then try to polish a single turd it's easier to delete all the code than to delete it piecewise step six break your code into pieces Big Balls of mud are the easiest to build but the most expensive to

  24. maintain what feels like a simple change ends up touching almost every part of this code base in an ad hoc fashion what was easy to delete as a whole is now impossible to delete piecewise in the same we have layered our code to separate responsibilities from platform specific to domain specific we need to find a means to tease apart the logic a top quote start with a list of difficult design decisions or design decisions which are likely to change each module

  25. is then designed to hide such a decision from the others D parnis instead of breaking code into Parts with common functionality we break code apart by what it does not share with the rest we isolate the most frustrating parts to write maintain or delete away from each other we are not building modules around being able to reuse them but being able to change them unfortunately some problems are more intertwined and hard to separate than others although these

  26. single responsibility principle suggest that each module should only handle one hard problem it is more important that each hard problem is only handled by one module when a module does two things it is usually because changing one part requires changing the other it is often easier to have one awful component with a simple interface than two components requiring a careful coordination between them them quote I shall not today attempt further to define the kinds of

  27. material I understand to be embraced within that shorthand description loose coupling and perhaps I could never succeed in intelligibly doing so but I know it when I see it and the code base involved in this case is not that scotus Justice Stewart a system where you can delete Parts without rewriting others is often called Loosely coupled but it's a lot easier to explain what one looks like rather than how to build it in the first place even hardcoding a very variable

  28. once can be loose coupling or using a command line flag over a variable loose coupling is about being able to change your mind without changing too much code for example Microsoft Windows has internal and external apis for this very purpose the external apis are tied to the life cycle of desktop programs and the internal API is tied to the underlying kernel hiding these apis away gives Microsoft flexibility without

  29. breaking too much software in the process HTTP has examples of coupling to putting a cache in front of your HTTP server moving your images to a CDN and just changing the links to them neither breaks the browser https error codes are another example of loose coupling common problems across web servers have unique codes when you get a 400 error doing it again won't get the same result a 500 may change as a result HTTP clients can

  30. handle many errors on the programmer's behalf how your software handles failure must be taken into account when decomposing it into smaller pieces doing so is easier said than done I have decided reluctantly to use latex quote making reliable Distribution Systems in the presence of software errors Armstrong 2003 earling OTP is relatively unique in how it chooses to handle failure supervision trees roughly each

  31. process in an earling system is started by and watched by a supervisor when a process encounters a problem it exits when a process exits it is restarted by the supervisor these supervisors are started by a bootstrap process and when a supervisor encounters a fault it is restarted by the bootstrap process the key idea is that it is quicker to fail fast and restart than it is to handle errors error handling like this may seem counterintuitive gaining reliability by

  32. giving up when errors happen but turning things off and on again has a knack for suppressing transient faults error handling and Recovery are best done at the outer layers of your codebase this is known as the endtoend principle the endtoend principle argues that it is easier to handle failure at the far ends of a connection than anywhere in the middle if you have any handling inside you still have to do the final top level check if every layer a top must handle errors so why bother handling them on

  33. the inside error handling is one of the many ways in which a system can be tightly bound together there are many other examples of tight coupling but it is a little unfair to single one out as being badly designed except for IMAP in IMAP almost every each operation is a snowflake with unique options and handling error handling is painful errors can come halfway through the result of another operation instead of uu IDs IMAP generates unique tokens to identify each message these can change

  34. halfway through the result of an operation too many operations are not Atomic it took more than 25 years to get a way to move email from one folder to another that reliably works there's a special utf-7 encoding and a unique base 64 encoding too I'm I'm not making any of this up by comparison both file systems and databases make much better examples of remote storage with a file system you have a fixed set of operations but a multitude of objects you can operate on although SQL may seem

  35. like a much broader interface than a file system it follows the same pattern a number of operations on sets and a multitude of rows to operate on although you can't always swap out one database for another it is easier to find something that works with SQL over any Homebrew query language other examples of loose coupling are other systems with middleware or filters and pipelines for example Twitter's finagle uses a common API for for services and this allows

  36. generic timeout handling retry mechanisms and authentication checks to be added effortlessly to client and server code I'm sure if I didn't mention the Unix pipeline here someone would complain at me first we layered our code but now some of those layers share an interface a common set of behaviors and operations with a variety of implementations good examples of loose coupling are often examples of uniform interfaces a healthy code base doesn't

  37. have to be perfectly modular the modular bit makes it more fun to write code in the same way that Lego bricks are fun because they all fit together a healthy code base has some verbosity some redundancy and just enough distance between the moving parts so you won't trap your hands inside code that is Loosely coupled isn't necessarily easy to delete but it is much easier to replace and much easier to change too step seven keep writing code being able to write new code without dealing

  38. with old code makes it far easier to experiment with new ideas it isn't so much that you should write microservices and not monolith but your system should be capable of supporting one or two experiments a top while you work out what you're doing feature flags are one way to change your mind later although feature flags are seen as ways to experiment with features they allow you to deploy changes without redeploying your software Google Chrome is a spectacular example of the benefits they

  39. bring they found that the hardest part of keeping a regular release cycle was the time it took to merge Long Live feature branches in by being able to turn the new code on and off without recompiling larger changes could be broken down into smaller merges without impa impacting existing code with new features appearing earlier in the same code base that made it more obvious when long running feature development would impact other parts of the code feature flag is in just a commandline switch it's a way of decoupling feature

  40. releases from merging branches and decoupling feature releases from deploying code being able to change your mind at runtime becomes increasingly important when it can take hours days or weeks to roll out new software ask any SRE any system that can wake you up at night is one worth being able to control at runtime it isn't so much that you're iterating but you have a feed laap feedback loop it is not so much you are building modules to reuse but isolating components for change handling change is

  41. not just developing new features but getting rid of old ones too writing extensible code is hoping that in 3 months time you get everything right writing code you can delete is working on the opposite assumption the strategies I've talked about layering isolation common interfaces composition are not about writing good software but how to build software that can change over time quote the management question therefore is not whether to build a pilot system and throw it all away you

  42. will do that hence plan to throw one away you will anyhow Fred Brooks you don't need to throw it all away but you will need to delete some of it good code isn't about getting it right the first time good code is just Legacy code that doesn't get in the way good code is easy to delete each and every single step that te is talking about resonates with me because I think it's it's important

  43. to find as a developer what framework what code what stack if you will works best for how you can do these steps you don't necessarily need to be able to accomplish all these steps in every single framework perfectly because you're going to be working with teams or you might be able to get to choose your own stack in that case if you can know how to do all this if you can know how

  44. to write codes so that you can be iterating it in the future then you're going to succeed the reason why I use the stack that I do the reason why I got into Lille the reason why I build software in the first place was because I loved the idea of building something fast and having this clear path into the parts that I'm going to have to delete rebuild iterate improve upon expand out

  45. contract uh extract and further more in the future building code with the idea that you're going to have to layer something else with the idea of I'm bringing this in and perhaps I'm going to replace it perhaps not or I'm building on top of something else or I'm wrapping something else all of that is with this goal in mind of one I need to solve the problem at hand but then two I

  46. need to build this in a way where I can build it better later I think when we're building code or when we're building software sometimes we forget that this is a complete learning process you never usually build the same application the same way twice even if you did let's say you built a complete application you scratched it or you moved on to a new company and you're like oh I now have the chance to build that same problem

  47. same solution again I doubt it's going to be the exact same even if you're like down to the tech stack but most of the time the choices that you make in the future are because you learned something while building code in the past if I was to build another product today I I don't necessarily have a a SAS idea in my mind I mean I have a bunch of SAS ideas in my mind but I'm not starting one just yet but I know the choices I would make to

  48. fix the mistakes that I made in the past I know the things that I've had to ex ract that were painful to extract that were painful to wrap that were painful to layer that were painful to compose and recreate the the points that I am still uh you know in te's words I am still deleting and rebuilding and I could have done a lot of that better but

  49. now I have in my mind of how I would fix that in the future how I would build so that it would make it easier to delete that code in the future so I learned a lot from these steps because it's something that resonates with my brain of how things work how things improve how things continue to learn and you continue to learn as you build but I think the key part here is when you're

  50. building software you're not just writing oh that's really good code and someone's looking a customer is looking at that and they're saying yeah I love that that's really good code no how can you build software that can change over time and that starts with the building blocks that starts with how you learn from the last project that you experimented on so yeah good code is easy to delete but it's also easy to know when to delete it so that you can continue to build over time continue to

  51. learn over time and build better software in the future so keep creating [Music]

just you here