Call us Toll-Free:
1-800-218-1525
Live ChatEmail us

 Sponsors

Software Projects Coding Convention

Mike Peters, 09-17-2008
C Variable names:

All strings (char[256] and char*) must be prefixed by a lowercase s, followed by first letter of every word in caps.

Example:

  char 
*sMyString;
 
char  sName[256];

All integers must be prefixed by a lowercase i, followed by first letter of every word in caps.

Example:

  int  iAge
;

Exceptions when you don't need to prefix a variable name by i, are the following variable names: maxlen, i, j, k

All longs must be prefixed by a lowercase l, followed by first letter of every word in caps.

Example:

  long  lYear
;

All booleans and flags (even if you're using an int to identify 0/1 condition) must be prefixed by a lowercase b, followed by first letter of every word in caps.

Example:

  int  bFirstTime
;
 
bool  bSeenBefore;

All arrays must be prefixed by arr, followed by first letter of every word in caps.

Example:

  char  arrNames
[256];
 
int  arrAges[100];

All pointers to variables that are passed by reference to a function, with the purpose of being modified by the function, must be suffixed with an uppercase P.

Example:

  int  GetName
(char *sNameP, int maxlen);

PHP Variable names:

All arrays must be prefixed by arr, followed by first letter of every word in caps.

Example:

  $arrNames
= array("Jason", "Adrian", "Steven");

All booleans and flags must be prefixed by a lowercase b, followed by first letter of every word in caps.

Example:

  $bFirstTime
= 0;

All other variable names must be all lower case. Multiple words separated with an underscore.

Example:

  $age
= 25;
 
$customer_age = 31;

Exceptions: $Row, $Result

Function names (all languages):

Function names must have first letter of every word in caps.

Example:

 
// PHP function
 
function MyFunction($variable)
  {
  }

 
// C function
 
int MyFunction(int iVariable)
  {
  }

Exceptions: System functions and runtime functions should remain all lowercase (i.e. strcmp, stripslashes)

Constants (all languages):

Constant names should always be all caps.
Example:

$MAX_NUM_DAYS_IN_MONTH
= 31;

Indentation:

Avoid using spaces for indentation. Start your code at the far left corner and use tabs for indentation.

Example:

function MyFunction($variable)
{
 
// Do something
 
echo "Hello World";

 
// Check something
 
if (1 == 1)
  {
   
// Do something else
   
echo "Goodbye";
  }
}

Set tabs to 4 characters long. If you're using vi, edit ~/.exrc and add this line: set ts=4

When assigning values into multiple related variables, always left justify assignments

Example:

   
// set post username/password
   
$input['a']      = $account_id;
   
$input['p']      = $password;
   
$input['s']      = $sessid2;

Curly brackets:

Always place curly brackets on a separate line.

Example:

if (1)
{
 
// Do something
  // ...
}

Never ever include a curly bracket on the same line as your condition.

Function return values:

All functions must return an int or long value of 0 to indicate failure or a value higher than zero to indicate success.

Example:

int TestSomething
()
{
 
// Initialize
 
int iResult = 0;

 
// Test here
 
if (1)
  {
   
// Set returned result code
   
iResult = 1;
  }

 
// Return result
 
return iResult;
}

If statements:

If statements must use curly brackets per every condition block, even if it's only one line of code.

Example:

// If 1 equals 1
if (1==1)
{
 
// Do something here
}
// (Else - 1 does not equal 1)
else
{
 
// Do something else
}

Spacing:

Comment, followed by one line of code, followed by one line of space.

Example:

 
// Store 1 into my_variable
 
$my_variable = 1;

 
// Display the value in my_variable
 
echo $my_variable;

Exception: No need to add a line of space after an opening curly bracket.

Code process flow:

Avoid using a return/exit in the middle of your code. Every function should have a single return at the end.
Use do {} while(0) loops with breaks to control execution.

Example:

int VeryLongFunction
()
{
 
// Initialize
 
$iResult = 0;

  do
  {
   
// Test something 
   
if ($condition)
    {
     
// Oops. We have to bail
     
break;
    }

   
// Do something
    // ...

    // Test something else
   
if ($another_condition)
    {
     
// Oops. We have to bail
     
break;
    }

   
// If we're up to here - all is well
   
$iResult = 1;
  } while (
0);

 
// Return result
 
return $iResult;
}

Comment style:

EVERY SINGLE LINE of your code must be prefixed with a // comment. There is no exception to this rule.
As for what each comment should say - a nonprogrammer reading your comments top to bottom, should be able to fully understand what the function is doing.

Example:

// Display Hello World
echo "Hello World";

// Check to see if 1 equals 2
if (1==2)
{
 
// 1 does equal 2, the end of the world must be coming
  // Display end of the world
 
echo "It's the end of the world as we know it";
}
// (Else - 1 does not equal 2)
else
{
 
// We're in good shape
  // Display all is well message
 
echo "All is well";
}

Every function must be prefixed with a // comment block outlining input, output and return parameters.
Start with a few lines describing what the function does, follow with a list of all input parameters, then all output (pass by reference) parameters and finally the function return value.
Include another empty line with // at the end of the function description
Use this block as a template:


// Attempt to charge customer and process order
//
// Input:
//  store_id    - Your store ID
//  product_codename    - The unique product codename
//
// Output:
//  order_id    - On return will hold order id
//  ResultStr      - On return will hold Error string
//
// Returns:
//  Order ID if successful or 0 if failed
//
function do_checkout($store_id, $product_codename, &$order_id, &$ResultStr)
{
}

Other important Good Programming Practices:

1. Initialize all variables BEFORE using them

Example:

function MyFunction()
{
 
// Initialize
 
$iResult = 0;

 
// Now do something
  // ...
}

2. In C, always use strcpySAFE, strcatSAFE and strscatSAFE instead of strcpy, strcat and strscat

Example:

strcpySAFE
(sMyString, "Hello World", sizeof(sMyString));
strcatSAFE(sMyString, "!", sizeof(sMyString));

3. In C, reset all handles to zero and use a do {} while(0) block to ensure you never miss closing a handle (would be fatal)

Example:

int MyFunction
()
{
 
FILE  *handle = 0;
 
  do
  {
   
// Open file
   
if (!(handle = fopen("test.txt","r")))
    {
     
// File doesn't exist - bail
     
break;
    }

   
// Do something
    // ...
 
} while (0);

 
// If we opened the file - close it here
 
if (handle) fclose(handle);

 
// Return success
 
return 1;
}

4. In PHP, although we currently have global_variables turned on, do NOT rely on it as we are phasing that out.
Use $_REQUEST['variable'] to access HTTP_GET and HTTP_POST variables
use $_SERVER['variable'] to access server variables
and use $_COOKIE['variable'] to access cookies

5. Avoid using exceptions

6. When returning error strings (as a byreference sResultStr - in C, or $result_str - in PHP), always return meaningful error strings that a person other than yourself can understand

7. Try to avoid sprinkling new variables into the global scope. Try to keep all variables confined to the scope of a single function

8. Avoid long functions (two pages or more). Split to smaller internal functions as needed and prefix the internal function with an uppercase I for clarity.

Example:

function MyLongFunction()
{
 
// Wash clothes
 
IWashClothers();

 
// Now dry them up
 
IDryCycle();

 
// Notify master that laundry is done
 
INotifyMaster();
}

9. Avoid reusing the same variable in a function for two different purposes (unless it's an i, j, k loop counter)

10. As you develop new functions - "Black box test" your functions in a standalone environment, by calling them from a test shell script.

Then after committing your code to the live environment, "White box test" your code by running through a complete cycle start to finish.

Anders, 09-18-2008
Wow! Thanks for sharing. This is great stuff

David, 09-18-2008
EVERY SINGLE LINE of your code must be prefixed with a // comment. There is no exception to this rule.

*twitch*

You guy really need to look at DocBlock. Make those comments signal, not noise.

Adrian Singer, 09-18-2008
Thanks David - we did look at DocBlock in the past and weren't impressed.

Adding a line of comment per every line of code, takes a few more seconds and helps both the programmer writing the code as well as future ones who will be reviewing and working on your code.

cherouvim, 09-18-2008
hungarian notation looks really bad

Mike Peters, 09-18-2008
There’s still a tremendous amount of value to Hungarian notation, in that it increases collocation in code, which makes the code easier to read, write, debug, and maintain, and, most importantly, it makes wrong code look wrong

David, 09-18-2008
> Avoid using exceptions

Wait a sec... I just got to the end. What the hell is wrong with you people? Why are you setting out to make your code as verbose as possible?

The fewer symbols used, the fewer opportunities for mistakes, and the easier it is to hold the code in your head. Exceptions reduce the amount of code, and without them you're overloading the return value of a function to do two things - return a result OR return an error. Not a good idea.

David, 09-18-2008
On the comments...

Lets say you were working in assembler. Would you comment every single line? I hope not, because the "logical blocks" in asm aren't lines, they're groups of lines.

But the same thing goes for C and PHP - comments should express the "why" of the code rather than the "how", and "why" happens at a higher level of abstraction than the line. Comment the task, otherwise you end up in the reductio ad absurdum position of:

// echo "hello world"
echo "hello world";

where your comments are just noise.

(Agreed on Hungarian notation, BTW - there's a really good joelonsoftware post on the difference between apps hungarian and systems hungarian which is worth reading).

Adrian Singer, 09-18-2008
David - Love your comments!

Exceptions are a very powerful tool but can be devastating in the wrong hands.

We have a very distributed work force, where different engineers come from different backgrounds, work from remote locations across the globe and posses different skills.

To keep things manageable and reduce the likelihood of human error (i.e. forget to catch an exception and the entire script goes kaput), we do not like exceptions. Think of it as a way of sticking to the lowest common denominator.

As for your note about comments, we are not looking to duplicate the exact code in the comment, but rather use the comment to explain the why and how.

For example:


// Display greeting to user
echo "Hello user";

// If this is the first visit to the page,
if (empty($_COOKIE['beenhere']))
{
 
// Show first time notice
 
echo "Looks like this is your first visit. There are a few links you may want to check out: ";

 
// Save 'firsttime' cookie so that we won't display the
  // first time notice on the next visit
 
setcookie()...
}

If your code is going to be shared by hundreds of engineers, most of which are not going to communicate with you, the absolute best way we found to keep the code readable is to use one comment per each line of code.

David, 09-18-2008
Adrian - It took me years of saying "Exceptions are just gotos" before I finally got what they could do for me, so I completely understand your approach. In fact, I push for web frameworks for a similar reason - it forces developers of varying skill levels into the same straight-jacket.

I think a post about why you mandate certain rules would have been a lot more interesting than the list of rules themselves. You seem to think that you need to "dumb-down" the rules as the team size increases. I wonder if that's a universal rule.

What industry are you working in, to have so many developers working on a single codebase?

Adrian Singer, 09-18-2008
Hi David,

You bring up a great point. We'll be writing a few posts about the tools and techniques we use to manage large distributed teams of engineers, all working on commercial projects where "time is money", coding under the extreme programming methodology where your code goes to production right away. (Very different from doing open source)

In such an environment, one of the most important lessons we've learned is that you want to do everything possible to eliminate the potential for human error.

STL templates, exceptions and class inheritance are all great tools but often too advanced for the average engineer to comprehend.

Software Projects is a full-service Internet Marketing & Web development firm. We provide a platform of 81 services, that powers the entire e-commerce, crm, erp, billing and analytics back-end for 3,000 companies in 14 countries.

You can read more about our platform here.

We're always looking for talented engineers to join our team. Please visit this page if you're interested.

David, 09-18-2008
Ack. My voice is completely off today, I'm coming over as unfriendly and confrontational, and I'm not trying to. Let me try again...

I'd be really interested to read about the process you went through to reach these rules, because I work in smaller teams and they seem a bit draconian to me (I'm still not convinced by the one-comment one - "Display greeting to user" doesn't add any useful information to "echo "Hello user"" IMO). I'm going to subscribe in the hope that you'll put together some more stuff on this subject, because it looks like you have some very interesting experiences to share.
Enjoyed this post?

Subscribe Now to receive new posts via Email as soon as they come out.

 Comments
Post your comments












Note: No link spamming! If your message contains link/s, it will NOT be published on the site before manually approved by one of our moderators.



About Us  |  Contact us  |  Privacy Policy  |  Terms & Conditions