In the book The Pragmatic Programmer, the writers mention the programming by coincidence concept. It explains what it is, why it is caused, what are the dangers you may encounter and it compares with a landmine field in a war.
Do you ever watch old black-and-white war movies? The weary soldier advances cautiously out of the brush. There's a clearing ahead: are there any land mines, or is it safe to cross? There aren't any indications that it's a minefield—no signs, barbed wire, or craters. The soldier pokes the ground ahead of him with his bayonet and winces, expecting an explosion. There isn't one. So he proceeds painstakingly through the field for a while, prodding and poking as he goes. Eventually, convinced that the field is safe, he straightens up and marches proudly forward, only to be blown to pieces.
The soldier's initial probes for mines revealed nothing, but this was merely lucky. He was led to a false conclusion—with disastrous results.
As developers, we also work in minefields. There are hundreds of traps just waiting to catch us each day. Remembering the soldier's tale, we should be wary of drawing false conclusions. We should avoid programming by coincidence—relying on luck and accidental successes—in favor of programming deliberately...
But I am not really satisfied on the way they describe the "how to overcome it" issue. Yeah, you have to think ahead before writing the code, but how to practice that? The only thing I can think is by adding features to existing Open source projects, where you must have knowledge on both the "what I am doing now" and the "How the other pieces of code are working", and it is not that applicable when you are writing your own projects.
a summary from your posts:
- Don't guess your next move, prove it is correct
- Unit test and refactor much as possible, when necessary
- Add features–compile–test often
- If you can't explain the code to a noob, you're probably programming by coincidence.
BTW, it is hard to accept an answer, it is really hard. All answers are really great :)