I just came across a really cool blog post written a couple of months ago by Evan Light where he proposes that we 'write the first one ugly':
To overcome paralysis, for small chunks of code, it is often better to just write whatever comes to mind – no matter how awful it may seem at the time. Give yourself permission to let the first version suck.
I think this is a really good piece of advice and it seems along the same lines as a suggestion from Uncle Bob in Clean Code:
When I write functions they come out long and complicated…then I massage and refine that code, splitting out functions, changing names and eliminating duplication…all the whole keeping the tests passing.
I find myself following a similar approach to Evan these days whereas previously I'd probably have spent a lot of time thinking through the problem in my head trying to come up with a design I was happy with.
I agree with Evan that it's frequently easier to see a clean way to solve a problem if you actually have some sort of code in front of you even if it is a terrible solution.
If I get stuck I tend to copy and paste other code, break encapsulation of objects, write long methods and so on. Then after I have something actually working I'll go back and clean it up.
Sometimes I don't see a way to write a piece of code more cleanly so I'll leave it alone until the next time we're working in that area of the code base, an approach that Joshua Kerievsky expands upon in a post he wrote a few months ago titled 'sufficient design'.
I'll leave the final word to Simon Harris who made the following observation on twitter which I think is pretty accurate:
Ive said it before the difference between great developers and hacks is: the former clean up after themselves.