Your first idea is probably bad 👎
To write is human, to edit is divine.
These are the words of horror fiction writer Stephen King.
It is a widely-accepted fact in writing that what your first draft is not very good. Instead, the magic is in the editing. In the repeated improvements made to the text. Here is how author Wiliam Zinsser expresses it.
Rewriting is the essence of writing well: it’s where the game is won or lost.
The same is true for programming. Unless you happen to be divine—or at least a better programmer than Stephen King is a writer—what you write on your first try is rarely good.
The freshly written code almost always has something wrong with it. It’s unclear. It’s inefficient. It’s overly complex. It’s rigid. It’s inconsistent. It’s full of unnecessary duplication. It’s full of magic numbers. It lacks readability. It’s hard to debug. It can be misinterpreted. It doesn’t integrate smoothly with the surrounding code.1
Just as in writing, there is a need for editing in programming. It is important to realize that software is an evolving entity, not a finished product. You need to edit your code to improve. You need to rethink, rewrite, refine, and refactor. Nobody expects you to get it right the first time, or even the second time.
Your goal, is to do as little as possible, as well as possible, and to strip every statement to its cleanest components.
Most of this rewriting will be based on the first draft you wrote, tightening it up step by step. To do so, it often helps to put yourself in the shoes of the reader. If you were new to this code, would it be easy to understand? If you were reviewing this code from a colleague, what would your comments be?
You may resist rewriting because you find it a chore that you’d rather avoid. Then keep in mind that the effort you save by not making the code easier to understand and maintain will have to be paid by each individual (yourself included) that will need to interact with this code in the future.
It could also be that the solution you just wrote feels like the obvious, best, or only solution to the problem. Then it can be helpful to challenge yourself using the find three solutions rule of thumb.
If you do get into a habit of rewriting and editing your code, you’ll likely find it to be rewarding. I have a strong feeling both you and your colleagues will thank you. 😊
-
This is a a paraphrase of a similar paragraph in On Writing Well by William Zinsser which describes all the things that can be wrong with a freshly written sentence. ↩︎