How To Write Clean Code Quickly
One of the coolest questions I got at TestMu conference was this: How to write clean code quickly?
It sounds like a simple question at first, but it does have a lot of depth, if you start pondering about it.
Let’s start with the obvious: Do more of it.
Write more clean code. The more you do something, it flows more easily from your mind to the keyboard, then the screen, and from there directly to production. Sometimes too quickly, but let’s not talk about that.
Here’s something I’ve learned through my long journey in coding: The code you write first, is never (neeeeeveeeeer!) the cleanest code. It’s a draft. Maybe even a working one. Probably only partially, because I didn’t think about everything.
But then, I focused on making it work. The code was never in the shape I wanted to leave when I’m done.
So, a quicker way to clean code, is to code everything at least twice. It could be from scratch, but iteratively works too.
“But”, I hear you say, “but if I touch it again, I will break it!”
You know where this is going, right? The quickest way towards clean code (at least for me) is Test Driven Development.
Apart from the design aspect, which moves the code toward cleanliness, TDD has something else. TDD takes into account the developer’s mind. Because, we usually focused on making it work first. We can’t do both function and form well together.
The separation between function and form is built into TDD. The two steps (green and refactor) leave space for both, and let us concentrate on the one we’re working on.
When I’m refactoring, I’ll do my best job, without breaking anything, and finish early. Plus, since the process is iterative and incremental (as is our thinking), we get a gradual, small step refactorings to where we want to go. As opposed to big leaps, which are more risky and therefore slower.
And, hear me out, if we pair on that code, two persons will have a chance on producing the best clean code they can create, even faster.
If you gotta go fast, drive TDD style.
If you, or your code, are not ready for TDD yet, don’t fret. There’s a workshop for that. Clean Code workshop. Not the fastest way to get there, but you will get there.