Any creative process, be it writing code, literature, slides, or anything, is susceptible to what is commonly called writers block. One of the common ways this happens is when we start being more afraid of writing something wrong than of writing nothing. We get paralyzed by fear. While writing for my book (Five Lines of Code), I got this fantastic advice:
Write the first draft with your heart, then rewrite it with your head.
The effectiveness of such a simple statement was astounding to me. I had often sat down to write and, after several dozens of minutes, still found the screen blank. I knew ‘kind of what I wanted to say, but not how I wanted to say it.’ Trying to solve both the ‘what’ and the ‘how’ at once is exponentially harder than doing each apart.
After learning this advice, I experienced that ‘any text’ is immensely more valuable than ‘no text,’ and no matter the initial quality, there was no issue so big I could not solve it afterward. If my file were empty, I would write whatever came to mind, no filter, just whatever I felt like. Then I would go back to extract the essence: the headings. I would remove bad ones and arrange the rest with the best flow. Finally, I would fit the drafted text to these sections rewriting bits along the way.
Soon I realized that I have been following this principle when coding for years. When I sit down to write code, I have learned never to think about writing the best or even good code. If we get bogged down with all the ways to write bad code:
- incorrect style
- difficult to read
- bad architecture
then it is challenging to get started at all.
I usually start by doing what is called a spike; Some code that never goes into version control (or production of course). I spike a quick prototype to verify that I know what to build. As this code is quickly deleted, there is no reason to make it nice — quick and dirty, quick being the keyword. Using the knowledge from the spike, I write a specification (usually in the form of an automated test). Then I set about to implement the actual functionality. I don’t care about any rules or guidelines. I only want to make the code compile and pass all the specifications.
When the functionality is there, now is the time to think about making it good before sharing it with others. I do this by refactoring it. I have done refactoring like this so much that I am confident, no matter how bad my initial code is, I know there is a way to make it awesome. Finally, I push it to master.
I have found that completely segregating implementation and refactoring is a much more pleasant and faster process. Leading to the title of this post:
Code with your heart, then refactor with your head
If you are interesting in learning refactoring, my book is a great place to begin your journey: Five Lines of Code.