Compared to most people on this site I am admittedly a novice. I wanted to get some advice from the pros on how to avoid making stupid errors in your code.

Is there anyone else who had the problem when they were first starting out of missing some detail that causes big problems? Are there any habits or behaviors that helped you over come this.

+32  A: 

Here's a list of common pitfalls, and/or suggestions to avoid them:

  1. Experience, the best way to avoid mistakes is to have already had them happen to you.
  2. Review other people's code
  3. Have other people review your code
  4. Use source control, even if you are the only developer
  5. Review all of your changes before doing a commit to source control
  6. Consider using a more modern language that makes it harder for you to make mistakes
  7. Comment your code extensively
  8. Refactor your code early and often
  9. Fix bugs before adding features
  10. Create extensive test cases, because knowing about your mistakes help you avoid future ones faster.
  11. Learn and use design patterns.
  12. Avoid code duplication at all costs, try to never copy/paste blocks of code
  13. Read about specific common pitfalls in the programming language you're using
Brian R. Bondy
Experience is a pitfall to be avoided? :-) You might want to rewrite your first sentence.
Modified my opening line instead. Thanks :)
Brian R. Bondy
Great list, vote++
I especially agree with #12. I use copy and past far too much because I'm trying to save time. I could just as well write macros or use my code snippet instead and save far more time.
Anthony Potts
+5  A: 

Peer code review and unit testing. Only experience will help you stop making the mistakes, but these things will help you learn about the mistakes that you're making early.

+11  A: 

I found writing code or algorithms on paper on, or at least in my head before starting to code. It gets the problem a little clearer in your mind and you don't just fire off and start coding when you can perhaps make silly mistakes being too eager.

+4  A: 

Like most other acquired skills, practice makes perfect. Keep training.


We all make stupid mistakes, because we're human.

I'm a novice, but I've worked with a number of seasoned professionals that make the same silly mistakes that I make. These are the mistakes that you'll learn from and be able to correct almost immediately.

Aside from that, the best thing I can recommend is checking for errors after every small piece of code that you write. It feels great when you can churn out hundreds of lines of code an hour, but you'll soon come crashing down when you have a thousand errors and a thousand lines to check.

+1  A: 

Comment well.

Space out your code well.

Have meaningful variable names.

+5  A: 

It's like with everything else you will do in life. From burning yourself on the fryer at a local fast food shop, to being an entrepreneur on his/her 3rd startup.

Make mistakes, learn from them, and better yourself - don't ignore them.

David McGraw
Also, accept that you will make the occasional silly mistake now and again, probably for the rest of your life, and don't worry too much - just be sure to keep an eye out, correct them when you spot them, and your experience will grow to eventually minimise their number and severity.
+10  A: 

I find that if I read through the diffs on all my code just prior to committing it to version control, I am almost guaranteed to find some mistakes. Double that effect (at least) if I've got someone else reviewing the code pre-checkin.

Matt Dillard
I'm still pretty new to source control, and I still carefully read all the diffs before committing. I have wondered whther this is unrealistic -- whether I'll inevitably relax that a bit as I get more used to it. I'm glad to know that I'm not alone in finding the practice worthwhile.
I almost always review my diffs before checking in anything, although that's more to ensure I'll write an accurate log message. Still, it's helped me find (and fix) bugs before.
Chris Charabaruk
It depends on your SCM/RCS/VCS workflow and system. I use Mercurial, a DVCS, so I make many atomic commits, perhaps every few minutes (I'm usually working in Python, so that would be a handful of changes), so it's really fresh what changes I think I've made. Commit early, commit often!
Matthew Schinckel
+4  A: 

I'll add another vote to "practice makes perfect" but with a slight admendment:

perfect practice makes perfect - a related saying is "practice makes permanent" so in other words make sure that what you're practicing is good coding habits that cut down on mistakes:

  • unit testing
  • readable code formatting
  • useful variable names
  • source control for revision history

and so on. I also highly reccommend taking a look at good open source projects and seeing how they organize and manage the code. Good examples are even more important to learn from than seeing other people's mistakes :-)

+2  A: 

Good judgment comes from experience.

Experience comes from bad judgment.

This may sound overly simplistic, but I try to follow this mantra. I try not to make the same mistakes I have made before.

Jason Jackson

Practice - the more code you write, the more experience you will gain

Re-use code - code which has been used a lot is least likely to contain defects

Defensive coding - minimize creation of risky code, avoid edge condition effects

Testing - look at TDD unit testing (not traditional unit testing) - which mean documenting the expected code behavior and creating code which tests it. More code means more experience, more automation, higher confidence

Cade Roux
+2  A: 

You're making a good start - recognizing that you don't have it all figured out. None of us do.

Make sure you understand the domain - that will eliminate some errors right off the bat. Know what you are solving, and then go about trying to develop the solution.

Have an approach to development. I use a test-first approach, but it isn't the only way. That provides me with a built-in checker that I'm still on course. I utilize my peers to bounce ideas off of, I've used pair programming before and found value in that.

If you develop a system to minimize the 'dumb' mistakes, you'll find they'll go away. Maybe a checklist would work. The Personal Software Process encourages that approach. Try it and see if it works.

I like to whiteboard my thoughts before I commit them to code. I like my peers to show me why I'm not right in my thinking first. If they can't, I'm reasonably certain I've eliminated some possible hurdles.

A LOT of this will come from experience, essentially from time doing what you do and learning from your mistakes!

+4  A: 

I find that if I'm having any particular trouble trying to fix a bug or think a problem through I'll take a 5-minute breather. By the time I get something to drink or just relax and come back to the problem I tend to be more focused and less stressed.

Zee JollyRoger
+1  A: 

Generally, BIG mistakes come from diving in and writing software prior to thinking about it. I employ 2 programmers and here's what I insist that they do. It makes a big difference.

Draw the screen you are designing on paper and determine how things work as much as possible before coding. Show it to your boss/client/someone else. Explain it to them. Get them to critique it.

Never start writing code until you have thought about it as UML. You don't need to be a UML expert but class diagrams showing:

  1. Inheritance
  2. Aggregation (eg this site consists of users, users make multiple posts, posts can have multiple comments by other users)

Will make a massive difference to not thinking about it at all.

Keep your functions small - never more than say 30 lines, often less. This will help you structure your code.

+2  A: 

Always have the "Keep It Simple" attitude!! You have less chance on making mistakes if you keep things simple.


+2  A: 

Avoid the urge to start writing code before you fully understand the problem. If you only understand part of the problem you're likely to spend time reworking the design later. Get the big picture clear in your mind or on paper, then start coding.

Cory House
Or get the picture right by talking to someone, preferably while writing and/or drawing on a whiteboard.
Jared Updike
+1  A: 

For me, when I stared to code I use to put a kind of 'to-do' list in a method detailing what I had to do at each stage to complete the job. For example if I had a method that was to get a customers name I would write something like..

public string GetName(int custID) {

        // Create local variables

        // Get the connection string from the config file

        // Create Try Catch Finally block

        // Create SQL parameters 

        .... etc


I would not leave these in as comments but would delete them as I did the task. I don't do it anymore to be honest and I doubt that you would need to do it for too long.

Also, I would recommend that if you are trying to learn something new that you do a 'real' project and not just examples from a book or website (even if it's just a little app for yourself, get it to work). Reading a book on code is no substitute for getting stuck in.


We all make mistakes. The geniuses are the ones who simply keep them on the cutting board.

Practice, do frequent code reviews (I mean, frequent), keep an extensive version history, and make sure you know where to find someone who has learned how to keep his mistakes better hidden.

+1  A: 
  1. Do not affraid of mistakes - this is the best way to learn new things
  2. This is very important to have a weekly code review - with a pro
  3. code at home - it will help you improve yourself faster
  4. read others code - open sources code are the best way to learn new things
+1  A: 

My only advice that hasn't been mentioned already, and that helps me on a regular basis, is this: before I make any significant change, be it code or documentation, I will always take a 10-15 minute break before actually finalising the change. Usually taking the break will let me come back refreshed and - more importantly - not as invested in the change, and most of my stuff-ups become glaringly obvious because of it. This is usually more helpful when you're the only person working on something, otherwise you can just get a Peer Review which is generally superior.


Static analysis tools are very useful. Findbugs also provides information about why particular practices are harmful to your programs.

Michael Barker
+2  A: 

Patterns - develop or borrow and USE patterns in your work. Some example patterns: consistent use of variable names, consistent location for incrementing counters, consistent placement of error reporting, etc.

One vital aspect of using patterns effectively is their visual appearance. One bad practice that amazes me for its common usage is the placement of open braces at the END of a line rather than at the beginning of the next line. For example, this is good practice:

void MyMethod(String some_input)
   if (some_input == null)
      some_input = "";

The same method written using a common but bad practice would look like this:

void MyMethod(String some_input) {
  if (some_input == null) {
    some_input = "";

If there's a missing brace somewhere, it's very time consuming to find it!

Richard T
I think Patterns refer to Design Patterns, not coding style.
Jared Updike
Personally if prefer line end style because of the additional compactness, however I recognize that it is more easily abused than new line style. Line end does require that the coder rigorously sticks with an indentation regime, but if that can be assured it is marginaly more efficient.IMHO YMMV :)
Just because you don't use a particular practice, that doesn't mean that practice is bad.
Scottie T
An editor with auto-indent and paren highlighting makes this a non-issue.
Justin Smith
Not quite, Justin; all the ones I've seen are fooled by mismatched braces, parens, brackets, etc, inside quoted strings.
Richard T

Most of the answers here are fairly general, but there are a number of practical things you can do when developing code to make mistakes less likely. Precisely what they are will differ between languages but for example a common source of bugs are hanging if statements - many languages for not insist you bracket code if it's a single line - e.g.

if fred==bill dosomethingtofred() else dosomethingtobill();

This will often give rise to bugs - particularly if the code is edited later. I've also not bracketed the test here as again that's permissible in some languages and is a potential error generator. Myself I will always, without exception, structure an if statement in full layed out over the full linage e.g.

if (fred==bill) {
else {

(note personally I prefer line end {. Some people frown on it and in a cooperative environment it is probably better to use the new line style, however I work as a consultant primarily writing code that will be maintained by myself and I rigorously adhere to indentation standards, so the additional compactness of the code pays off)

Similar techniques can be applied in most languages over a wide range of code constructs. I'd suggest you examine carefully where you are making the stupid mistakes then consider what code structures would prevent you from doing so then and use them every time going forward. Myself I have a fairly wide range of these constructs built up over several years (for another example all my sql is layed out the same way). As well as reducing stupid errors this also has the additional advantage that I can come back to code after several years and pick up the functionality very quickly.


Do everything you can to understand your mistakes. Write down what went wrong, everything you tried to fix the error, and what finally worked. I use this method to force myself to slow down and stop guessing blindly. If you do this long enough, you'll develop a detail-oriented work habit that should decrease your mistakes.

Scottie T

I believe in a simple thing.

Code once, code right.

And to get that (for me anyways), I need to completely visualize the issue mentally before doing anything. If I do not understand a problem completely, I am very hesitant to continue.

That said, sometimes you have to cross the line, and just see whats on the other side without knowing.


Don't be afraid to ask questions if you don't understand something. Most of the biggest mistakes I've seen have been the result of someone who doesn't understand the requirement thoroughly and doesn't ask further questions to make sure that the program is doing what is intended. Or someone who uses they code they don't understand and don't ask for an explanation of and then doesn't understand why it won't work in their specific circumstances. Then there are people who don't understand their data model well enough to determine if their queries returned the right answer, it isn't enough for it to run, it needs to return the right data. Again, they didn't ask questions to get a better understanding. I've sat in meetings and watched people nod their heads and agree with something and known they were going to do the wrong thing just from their body language. But it's hard to help someone out who won't admit he doesn't understand.