Sunday, June 26, 2011

Marwan's Programming Guiding Rules

Ok, now that I have expose my view on maxims, I can write my own ! (but remember, don't trust the maxims !)

I'll start with pure coding guidelines (and keep the rest for later.)

copy/paste are evil !

(with its corollary: copying code implies copying bugs)

This one is classic (at least for my students): whenever you want to copy/paste some code, you should reorganize it. Most of the time, a function (or something similar) will be useful later, and even if there'll be only one copy, you will probably find a better way to write it.

Just take some examples: here it is two function on linked list, a simple first place add and a sorted insertion, with copy/paste:

typedef struct s_list *t_list;
struct s_list
{
  t_list next;
  int    data;
};

t_list add(int x, t_list l)
{
  t_list t;
  t = malloc(sizeof (struct s_list));
  t->data = x;
  t->next = l;
  return t;
}

void insert(int x, t_list *l)
{
  if (*l == NULL || x < (*l)->data)
    {
      t_list t = malloc(sizeof (s_list));
      t->data = x;
      t->next = *l;
      *l = t;
    }
  else
    insert(x, &((*l)->next));
}

Now, the version of insert without copy/paste:

void insert(int x, t_list *l)
{
  if (*l == NULL || x < (*l)->data)
    *l = add(x,*l);
  else
    insert(x, &((*l)->next));
}
First, the later version is shorter. But that's not all, in the second version, the reference to the size of  the struct is done in one place. If you finally want to use a specific allocator (such as a recycling pool) you have one change to make, not two nor more.

Another toy example, with "one copy" (no need to write a function), we implement FIFO queue using circular list (this is only the push operation):

// with copy/paste
void push(int x, t_list *q)
{
  t_list t;
  if (*q)
    {
      t = malloc(sizeof (struct s_list));
      t->data = x;
      t->next = (*q)->next;
      (*q)->next = t;
      *q = t;
    }
  else
    {
      t = malloc(sizeof (struct s_list));
      t->data = x;
      t->next = t;
      *q = t;
    }
}

//without
void push(int x, t_list *q)
{
  t_list t;
  t = malloc(sizeof (struct s_list));
  t->data = x;
  if (*q)
    {
      t->next = (*q)->next;
      (*q)->next = t;
    }
  else
    t->next = t;
  *q = t;
}

Again, the code is smaller and simpler to verify. Those two example are very basic, and most programmer will probably use the second form intuitively, but in more complex situation, taking as guideline to avoid copy/paste may save you from long nightmarish bug hunt.

Any programming features is good as long as it fit your need.
There's no reason to not use a feature in your programming language  as long as you understand it and it do the job. If it's possible, it means that somehow, it was meant by the language designers for a good reason (or, else, they should have find a way to forbid it.)

When teaching programming, I often heard students arguing about bad practices, rules they have read on the net that they don't really understand. Most of the time, theses rules only take sense in a precise context or express a taste rather than a reasonable motivation.

The main goal of programmer is to make its code works, it's not to produce shinny piece of code or perfect models of how to code. This lead us to my next rule:

The end justifies the means.
To understand this one, we must define the end and the means. The end is your goal, what my program should do. But it's also all the requirements linked to it: should it be fast ? should it be robust and reliable ? what will be its life cycle (one shot or  high availability permanent run) ? would it be extended ? ...

The means deal with how you will produce it and it's strongly connected to the end: don't spend to much time on code for a one shot script, make it works, on the other hand remove all quick and dirty implementation from a production release !

Building a program is most of the time some parts of professional work you're paid for. So, this is not a challenge of best programming practices, there's no jury's prices for nice attempt: you have to make it works the way your future users expected it to work. If they ask for simple script that will save them hours of boring manipulation, they don't want months until you find it finally presentable, the want it now !

The important point is to define the correct goals, and make the right efforts to achieve these goals.

This also means that any tricks are fine as long as it makes your code works. Again, students some times seems disappointed by some hacks they found in some piece of code. They saw it as cheating as if finding a way to get around some difficulties is not elegant and should not be tolerated !

Coding is no game, you can have fun doing it, but there's no place for ridiculous honor code. You will find that the satisfying users' expectations will probably force you to produce code as clean as it can be and that you won't need arbitrary rules to guide you.

Take for example the use of goto and the particular cases of goto into the body of loop: goto is generally considered evil and goto inside a loop is the probably the most heretic things you can do. But, there are some cases where this can be useful. The best known example is the Duff Device example of smart loop unwinding, take a look at it, it's worth the read. I will use a simpler example, not focus on optimization, that I found more striking.

The idea is simple, you have a list or an array and want to print each element separated by a ';', by separated we really mean that the separator is between each element and not after, thus the last element will not be followed by a ';'. There are several ways to do that, let's take a first example:

void printArray(int tab[], size_t count)
{
  size_t i;
  size_t i;
  for (i=0; i < count; ++i)
    {
      if (i > 0) // not the first time
        printf(";");
      printf("%d",tab[i]);
    }
}
Ok, this is not the best version you can write, but it focus on the fact that the first case is handle separately. We can have done like that also:

void printArray(int tab[], size_t count)
{
  if (count)
    {
      size_t i;
      printf("%d",tab[0]);
      for (i=1; i < count; ++i)
        printf(";%d",tab[i]);
    }
}

In this version, the treatment of the first case is less obvious and we need to check the count. Now, take a look at this one:

void printArray(int tab[], size_t count)
{
  if (count)
    {
      size_t  i=0;
      goto start;
      for (; i < count; ++i)
        {
          printf(";");
        start:
          printf("%i",tab[i]);
        }
    }
}

We use a goto to skip the first printf in the loop. The result is better than the first version and it let appears the specificity of the first case. Of course, this is a toy example, and the goto version is not dramatically better in any way, but it illustrate the fact that dirty code can be useful and readable.

Keep it simple, stupid !
One of the classic ! Prefer the simplest path. When you can't figure out yourself how your code work, it means that it's too complex and will probably won't work. Here are some other maxims and quote on the subjects:

"Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it ?"  (Brian Kernighan, "The Elements of Programming Style", 2nd edition, chapter 2)
Smarter code means smarter bugs ! (me ;)
"There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies." (C.A.R. Hoare)
So, all those rules deal finally with the same issues: making your programs work ! That's the only things that really matter in programming.

No comments:

Post a Comment