views:

490

answers:

8

I was wondering, how a program can be written in a perfect professional style. Many times it happens that we write a very good program/code which gives the accurate output.One might use the best algorithm to solve the given problem.

But for a person who is reading your code for his/her reference, it becomes difficult to understand the code because of improper use of variable/function names.(And many other issues)

So how one can achieve this perfection of writing code in professional manner?

You can elaborate your thoughts by directly editing the following code. (Don't edit the code in the question :)

You can also rewrite the complete code at the end in professional way.Will be a lot of help.

(A simple heap sort algorithm in C)

#include<stdio.h>
#include<conio.h>

void insert(int i);
void swap(int *,int *);
void heap_sort(int);

int a[20];

void main()

{

        int n,i;
     clrscr();

     printf("Enter the no of elements : ");
     scanf("%d",&n);
     printf("\nEnter the elements : \n");
     for(i=0;i<n;i++)
     scanf("%d",&a[i]);
     heap_sort(n);
     printf("\nSorted array is : \n");
     for(i=0;i<n;i++)
     printf("\t%d",a[i]);
     getch();
}


void swap(int *p,int *q)
{

     int temp;
     temp=*p;
     *p=*q;
     *q=temp;

}


void heap_sort(int n)
{

     int x=1,i;
     while(x<n)
         {
   for(i=1;i<=n-x;i++)
   insert(i);
   swap(&a[0],&a[n-x]);
   x++;
         }
}



void insert(int i)
{

            int j=(i-1)/2,item=a[i];
     while((i>0) && (item>a[j]))
  {
   a[i]=a[j];
   i=j;
   j=(i-1)/2;
  }
    a[i]=item;

}
+4  A: 
  • Use spaces and new lines. Without them code in any style is hardly readable. Also avoid a wall of text style.

Look at this:

void main ()
{

    int n, i;
    clrscr ();

    printf ("Enter the no of elements : ");
    scanf ("%d", &n);

    printf ("\nEnter the elements : \n");
    for (i = 0; i < n; i++)
    scanf ("%d", &a[i]);

    heap_sort (n);
    printf ("\nSorted array is : \n");

    for (i = 0; i < n; i++)
    printf ("\t%d", a[i]);
    getch ();
}

It's better now, isn't it?

  • Avoid meaningless one-letter variable names. They are cryptic and convey no information to the reader (and to yourself six months later).

  • Add comments where necessary. If you see some part of code may not be clear on its own, comment it. If you use some hack or trick, describe it, what is it and why you need it. If you use some algorithm (especially for mathematical calculations), reference it.

  • Avoid very long functions bodies. If you see a function is getting too much stuff, refactor it. Extract common and repetitive pieces into shared and helper functions, so that a person reading your code can see the overview of the function.

  • Avoid magic numbers in your code. Don't put some abstract numbers (3, 17, 135 etc.) directly in your code. Declare constants somewhere and reference them in your code. This way it will only take on change to have consistent effect in your code. It's easy to forget to change... well, say, 3 out of 26 number uses in the code.

  • The same goes for text strings. Declare them somewhere, in resources, in external files, as string constants and use them in the code.

Developer Art
+2  A: 

Brace the foreach statements (etc) to make the scope of the loop obvious:

for(i=0 ; i<n ; i++)
{
    scanf("%d", &a[i]);
}
getch();

(etc).

Perhaps add some summary comments to logical blocks of code; not "add 1 to i", though!

Marc Gravell
+10  A: 

Take a read of Code Complete, one of the best books on this type of subject. You won't regret it.

spender
A: 

I'd start with placing spaces after your periods.

Fragsworth
I don't get you.Please give an example.
Ravi
WTF? There are only two periods in the code, stdio.h and conio.h, and adding a space will break the include.
Pete Kirkham
He probably means spaces after commas and semicolons. (And I agree.)
Jochen Walter
+1  A: 

Code should really compile without warnings

warning: return type of ‘main’ is not ‘int’

The use of unspecified argument lists is generally not considered good practice.

Run the code through something like astyle and it will indent it for you, and add braces if that's your style. Note that it's called 'artistic style' not 'professional style' as it's designed to make the code look nice, and activity which rarely adds as much value as it costs if done by paid employees.

Professionals do it for the money. If your job is to make a one-off program which does as little as this does, then there isn't much point adding that much more comments, using more explanatory variable names or manually tidying up the formatting. Documentation, record of design history and intent, clearly defined sub-system boundaries all matter on larger systems, but they are techniques for managing complexity. As a professional, your job is add the most value for the least cost. Quality, maintainability and testibility are values, as well as functionality; which values the organisation you work for weight the most will determine what you focus on.

Pete Kirkham
+1  A: 

I think that whenever writing code you should keep in the back of your mind, how easy will it be for another developer to understand what it is doing. Generally I'd advise the following.

  • Space the code out into logical chunks
  • Give variables meaningful names
  • Make sure your methods only have a single purpose that is clear by its name
  • Carefully comment the parts of code where the reason for it isn't explicitly obvious

Basically, if it looks like a wall of text and you find it hard undestand what its doing then its going to be a lot worse for the person who didn't write it.

Jon Mitchell
+1  A: 

Here are few changes style wise, so may differ from person to person but be consistent.

  • Add a comment at top of the file
  • Add space after comma e.g. swap(int *,int *); -> swap(int *, int *);
  • Add space after semicolon in for loop
  • Add space after and before operators e.g '=', '+' , '-'
  • Remove unecessary space after braces and main
  • Be explicit so add braces {} in each for loop
  • Group code lines in group and separate groups by newlines
  • Start while loop brace from same column

Here is modified code

#include<stdio.h>
#include<conio.h>

/******************************************** 
Write a comment about what this program does.
General overview
*********************************************/

void insert(int i); 
void swap(int *, int *); 
void heap_sort(int);

int a[20];

void main() 
{
        int n, i;
        clrscr();

        printf("Enter the no of elements : ");
        scanf("%d", &n);

        printf("\nEnter the elements : \n");
        for(i=0; i<n; i++)
        {
                scanf("%d",&a[i]);
        }

        heap_sort(n);

        printf("\nSorted array is : \n");
        for(i=0;i<n;i++)
        {
                printf("\t%d",a[i]);
        }

        getch(); 
}


void swap(int *p, int *q) 
{
        int temp;
        temp = *p;
        *p = *q;
        *q = temp; 
}


void heap_sort(int n) 
{
        int x=1, i;
        while(x<n)
        {
                for(i=1; i<=n-x; i++)
                {
                        insert(i);
                }
                swap(&a[0], &a[n-x]);
                x++;
        } 
}



void insert(int i) 
{
        int j = (i - 1) / 2;
        int item = a[i];
        while((i>0) && (item>a[j]))
        {
                a[i] = a[j];
                i = j;
                j = (i - 1) / 2;
        }
       a[i] = item; 
}
Anurag Uniyal
A: 

Getting rid of these "printfs" except the last one would certainly make your original program more professional. Other than that, professional developers usually take extra caution on error handling. For example, what if your program is invoked in the following way: a.out < input.lst where the content of "input.lst" is as following: 10 3 4 5

Codism