Hacker News new | ask | show | jobs
by stinos 3073 days ago
Like others said: experience. Training for a correct mindset.

For me, for basically every line of code written, and also for bigger pieces of code, I'll try to think of all possible corner cases which might prevent the the pre- and postconditions from being established. And make as few assumptions as possible.

It takes a while to develop that mindset, and it takes even longer to learn to write code which doesn't have problems in the first place. And I wouldn't even consider myself being really good at it.

Note that once you get a hold of it, you'll automatically start to write code which adheres to most 'best practices' like DRY, proper naming, short functions, you name it. These go hand in hand with fewer mistakes. In the beginning this will cost you time. But that is not wasted, as it'll teach you to do the right thing in the first place, and once you do that you'll have to spend less time debugging and the code will be clearer in the first place so less time lost reading and understanding it.

As a simple example take code from a person who does lack that mindset (despite having programmed decades more than I have) which I reviewed just today: if you just write bar[1].Foo() and don't have a strategy to either make sure bar does have enough elements, or else a strategy to properly deal with the error (as in, not just segfault, unless it has been established that is the way to deal with it) which will occur if you try to access that element anyway, the code is not good. So when I write even the simplest thing like bar[1].Foo() I automatically will wonder about that, ask myself 'can this occur'? If it's supposed to never happen I'll likely insert an assert. If it can be totally acceptable, wrap it in an if statement. If it's a user error, complain. Etc. But never ever just assume it'll be ok. And to do that, realize you must always reflect about everything you can think of.