I spent years writing code. I’ve spent time learning from people I’ve seen as gurus, working together on pair programming, solving novel problems, debugging horror stories, and modifying work that others have so carefully (or carelessly) put together. Nominally, that’s our job. But despite all the time I’ve spent writing code over the years, I’ve spent even more time reading it. Reading code is one of those activities that can be infuriating or pleasant. The worst is when you are reading code and think to yourself “who wrote this?”— only to do a git lookup and see your name.
I’ve led teams. Sometimes my guys, even the good ones, ended up taking much longer than any of us expected on a task. Digging into it with them it became clear it wasn’t because of them but because of who came before. The spaghetti they are digging through makes debugging hard, integrating new code even more difficult, and hard to help organize your thoughts around how to solve the problems at hand. At this point, I sometimes step in and help them clean up what they are looking at to make it easier to debug and integrate their work into.
The ability to produce clean code is one of the most essential skills. Clean code helps expedite code reviews, future changes, and ability to think through the problems at hand. Clean code lets us read less and write more. Finally, clean code practices give you the tools to fearlessly refactor spaghetti. Today, I want to talk about what I believe is the most important part of clean code practices, and how embracing it will help turn coding or refactoring large problems into solving many tiny ones: pseudocode.
The method is simple. Write out your solution as high level pseudocode in plain English. The higher level, the better. Then, each line in your pseudocode becomes a real method or function call, with essentially the same name as the line in your pseudocode. This forms the initial structure. Then, for each method, repeat the process. Write out the solution to the ask inside the method as pseudocode again. Repeat until you can’t reasonably break down anymore. At this point, methods are normally 5-20 lines long at most.
The same process can be applied to pre-existing code. Refactoring existing code using pseudocode can be simple and help you understand what you are looking at. If you are reading a method that is hundreds of lines long, start at the top and start grouping lines into activities. Then just give the activity a name and copy the code into a method. You haven’t changed the code at all, just moved it further down into a named method. You now know what you are looking at and have cleaned it up.
Congrats! You’re on your way to being a clean coder.
By Zach Melnick, Director of Software Engineering Solutions