Clear your mind and proofread your code when finished.
Chess mastery is a discipline which places a premium on consistency: One moment of hallucination can throw away hours of good work.
Someone once asked a grandmaster how to avoid such mistakes, and was told, "Sit on your hands!"
The advice was only partly in jest. There is a distinct tendency when analysing extended variations to get immersed in a particular set of crucial issues, and to lose track of more "obvious" concerns: Almost anyone who has played chess at all seriously has repeatedly had the experience of making a move after deep thought and realizing that it was an elementary blunder... immediately after releasing the piece. (The only remaining strategy at that point is to keep a poker face and hope the opponent trusts you too much to notice. It has been known to work!)
The solution is to deliberately cultivate the habit of completely clearing one's mind and re-examining the position and proposed move with fresh eyes right before actually making the move.
Programming produces a very similar phenomenon: It is very easy to get lost in a particular set of intricate considerations while coding up a function, and to lose sight of more elementary considerations, resulting in elementary coding blunders. Coding blunders will not usually cost you a tournament and a title, but it remains true that it is much more efficient to avoid them than to track them down later in testing.
As with the chess master, the master programmer eventually --- usually through painful experience -- acquires the habit of stepping back from each involved coding task once done, clearing the mind, and re-reading thoroughly with fresh eyes, looking for elementary mistakes.
It is not a natural habit, but once acquired it can make programming much more pleasant. You may even eventually find your code working first try on a regular basis, an experience akin to nirvana.
Go to the first, previous, next, last section, table of contents.