Philosophy of Code Quality

Is there a philosophy to code quality?  It seems like there are questions of style that don't just come down to one method that's demonstrably better.

 

Let's say I wanted to make a program to add two numbers passed on the command line and print the result.  A pretty simple program.  This could be:


int main(int argc, char **argv)

{

  int x = atoi(argv[0]);


  int y = atoi(argv[1]);

  printf(“%d“, x+y);

  return 0;

}

This works fine.  It could also be:



int main(int argc, char **argv)

{

  printf(“%d“, atoi(argv[0])+atoi(argv[1]));


  return 0;

}

This is shorter.  Whether or not this is better depends on how you define better.  Some issues:


  • If an algorithm can be implemented in fewer lines of code, then it's often easier to understand, because you can see more of it “at a glance”. 

  • If you're debugging this code, you're not going to as easily (if at all, depending on the debugger) be able to see the results of the atoi calls before they're passed to printf.

  • The variable names in the first version aren't very descriptive, but in the second they aren't there at all.  Not having the variables may increases the ease of understanding the algorithm by having less things to mentally parse when reading (instead of having to remember that x is the result of the first atoi and y is the result of the 2nd atoi, it's right there on the call where it's being used).

  • If a developer wanted to add functionality to the program by also printing the values being added (ie, “2+2=4“) then he could just reformat the printf statement in the first version, but with the second have to either rewrite it, or (as in the case of many programs I've seen) he'd just end up calling atoi two more times.  Which would be wrong.

I prefer the first form.