tags:

views:

217

answers:

10

I usually make lots of mistakes (logic errors, syntax errors) in the first attempt to accomplish some programming tasks. I have to write unit test to detect those bugs. This is especially problematic when I am in an interview. In that situation, I am under pressure and I can not test my code with compiler and unit test.

My question is that how can I write correct code in the first place? I know it is difficult. Is there any pragmatic approach to reduce bugs at the first time?

Thank you all.

I was required to write a function that receives a pointer to an int array and the size of the array. Fill that array with prime number. It's not a difficult problem at all. But I made lots of mistakes at the first time and keep finding out new bugs. Since it was a phone interview I was asked to type the answer and send it thought mail.

My first try

    void prim(int * array, int size) 
{ bool isPrime = true; 
for (int i=0;i<size;i++) 
{  
for (int j = 2;j<i/2;j++)  
{    if (i%j==0){
        isPrime = ture;
        *array = i;
        array++;

      }  } } }

It was a really bad idea to write code in gmail. I will never do it again. I knew the program needs two for loops. However there are some big problems in the code

  1. 'i' should not increase at the end of first loop.
  2. if i%j==0, isPrime should be false
  3. the array operation should be put at the end of loop when we find a prime

My second try, I added isPrime test, fixed some errors and resubmitted it.

    void prim(int * array, int size)
    {
    bool isPrime = true;

    for (int i=0;i<size;i++)
    {

     isPrime = true;
 for (int j = 2;j<i/2;j++)
 {
   if (i%j==0){
    isPrime = false;
  }

if (isPrime)

{
    *array = i;
    array++;
}
 }
}

There are still some fundamental errors in the code. But my time is up, I try to fix them in my third try.

  void prime(int * array, int size)
    {

   assert(array != null)
   assert(size>0)

    bool isPrime = true;

    for (int i=0;i<size;)
    {

     isPrime = true;
 for (int j = 2;j<i/2;j++)
 {
   if (i%j==0){
    isPrime = false;
  }

if (isPrime)
{
    *array = i;
    array++;
   i++;
}
 }
}

Finally. After the interview, I felt that I really massed up. I copied the code into my IDE, fixed all the bugs and tested it. I sent this to my interviewer and said sorry about that. I was really surprised by how many errors I could make in such a small problem. Final Version

#include <iostream>
#include <assert.h>
using namespace std;


void prime(int * array, int size)
{

    assert(array != 0);
    assert(size>0);
    if (size == 1){
        *array=2;
        return;
    }
    else {
        *array=2;
        array++;
    }
    bool isPrime = true;
    int testNum = 3;
    for (int i=1;i<size;)
    {
        isPrime = true;
        for (int j = 2;j<testNum;j++)
        {
            if (testNum%j==0){
                isPrime = false;
                break;
            }

        }
        if (isPrime)
        {
            *array = testNum;
            array++;
            i++;
        }
        testNum++;
    }
}
    int _tmain(int argc, _TCHAR* argv[])
    {
        int t[5]={0,};
        int sample[5]={2,3,5,7,11};
        prime(t,5);
        for (int i=0;i<5;i++){
            assert(t[i]==sample[i]);
        }
        return 0;

    }

strong text

+6  A: 

You won't like the answer, which is: be a programmer for 20 years.

Jonathan Feinberg
Although, even then...
Dan McGrath
+7  A: 

lots of practice :)

although i dont think a few minor syntax errors will bother an interviewer too much - as long as your theory is sound.

JT.WK
Maybe it's me, but asking someone to write a piece of code in an interview without some decent IDE is stupid - if it's complex there's no way you won't fail. Same with asking about some super "complex" code which is error prone on every single line, my answer always to such questions is "this code is depreciated/error prone so I would change it to a proper one, but since I have to give a good answer here it's blablabla".
Zenzen
Syntax errors may very well kill the interview for you, so if you expect to make errors, say so and indicate how you'd correct them,
Liz Albin
If you can't write code without an IDE, you may want to work on that.
Dean J
I didn't mean it like it, I just think coding complex stuff on paper during interviews is pointless because there's no way you won't make a mistake or two and some interviewers won't let it go.Personally I prefer checking someone's intelligence, as my last boss said: "it's easier to shape up a smart person's coding skills, than to learn a skilled idiot to think"
Zenzen
+3  A: 

Write comments first. Writing comments will help you specify the main objective of your code and will help later, if your code needs revision in the future. As for the interview, it will also help interviewer better understand the idea you are writing even if your code is a little bit buggy.

Li0liQ
A: 

You need to simply program A LOT, start with really basic programs, then more complex ones.

Also during my first years at the uni, when we had introduction to programming in Pascal and C we had to "code" on paper all the time. At first I found it stupid, now I remember all the mistakes (tests were constructed so they would contain all the most common mistakes, like if(x = y) etc.) so I started coding on paper in Java recently (though I'm still a java beginner).

Now I code all sorts of things (whenever I find a decent idea I code it) and I think it's the only way to improve.

Zenzen
+2  A: 

You seem to be asking two questions

  • How do I answer coding questions at interviews?
  • How do I write good clean code?

Answering the first question is easier than the second. Please note that if you don't tell the interviewers about possible problems they're likely to presume that you don't realize there are errors, and you won't know to correct them. Here are some suggestions

  • tell the interviewer that you expect there may be syntax errors on your first cut
  • describe your algorithm in words
  • write pseudo code first
  • write functions top down
  • talk your way through the problem with the interviewer
  • tell the interviewer how you correct the errors

As for the second question, practice. Practice. Write lots of code. And yes, test driven development is a very good idea.

Liz Albin
A: 

how can I write correct code in the first place

If this question had a trivial answer, we wouldn't have day jobs.

While there is some academic work on the "proveability" of software programs, there's no substitute for a logical thinking and attention to detail -- particularly if all you have is a whiteboard and a marker.

As others have mentioned interviewers generally give some leeway for syntax errors but gross logical mistakes are less likely to be ignored.

micahtan
A: 

I will tell you what works on me. An on-the-fly error detector addon will help you very much.

I use Resharper. Before using it i had too many error at compilation time.

2 weeks ago i had to use a clean visual studio (resharper not installed) and I compiled the source with almost no errors.

Some people say that this tool makes programmer lazy, but i don't agree.

JCasso
A: 

Slow is smooth, Smooth is fast

                   - Unknown

Take your time and think about the code. As you work/practice you will make less mistakes and you will get faster in your coding. Just like anything else when you rush to do something and don't think you make mistakes. The more you do that thing the more it becomes a reaction instead of a thought.

Matthew Whited
A: 

Practice. If you usually use an IDE at work or at school, spend one day every other week coding without it.

If you can give an example of the types of errors you're prone to, folks can probably give much more specific advice.

Dean J
A: 

Practise, use the right tools for the job, write lots of code, learn your tools, write more code, read books about programming, write even more code. You get the idea. Programming is hard work, and there aren't really any shortcuts.

That said, anybody giving a coding task at an interview expecting a result which will compiles cleanly and works out-of-the box is clearly mad, and you do not want to work there. Good managers use coding tasks to see how you approach a problem.

JesperE