yCMS Coding Standards/Guidlines

If you have any comments or suggetions, email them to david.

Functions

Content: All content must be one tab's length away from the bracket, one line below.
For example:
if ( $variable )
{
    $content
}

is right, but
if ( $variable )
{
$content
}

is not.

Function Names: Functions should also be named descriptively. We're not programming in C here, we don't want to write functions called things like "stristr()". Again, all lower-case names with words separated by a single underscore character. Function names should preferably have a verb in them somewhere. Good function names are print_login_status(), get_user_data(), etc..

Function Arguments: Arguments are subject to the same guidelines as variable names. We don't want a bunch of functions like: do_stuff($a, $b, $c). In most cases, we'd like to be able to tell how to use a function by just looking at its declaration.

Summary: The basic philosophy here is to not hurt code clarity for the sake of laziness. This has to be balanced by a little bit of common sense, though; print_login_status_for_a_given_user() goes too far, for example -- that function would be better named print_user_login_status() , or just print_login_status().



Variables

Variable Names: Variable names should be in all lowercase, words would preferably be separated with an _underscore_.

    For Example, $current_user is right, and $currentuser is ok, but $currentUser is unexceptable!

Please keep variables descriptive, but short; it is very time-consuming to have to write a long variable, such as $ycms_user_name_is_logged_in_and_is_admin_level. Variables such as that will not be tolerated.

Loop Indices: The only situation where a one-character variable name is allowed is when it's the index for some looping construct. In this case, the index of the outer loop should always be $i. If there's a loop inside that loop, its index should be $j, followed by $k, and so on. If the loop is being indexed by some already-existing variable with a meaningful name, this guideline does not apply.

    Example:


		for ( $i = 0; $i < $outer_size; $i++ ) 
		{
		   for ( $j = 0; $j < $inner_size; $j++ ) 
		   {
		      foo ( $i, $j );
		   }
		} 

Summary: The basic philosophy here is to not hurt code clarity for the sake of laziness. This has to be balanced by a little bit of common sense, though; print_login_status_for_a_given_user() goes too far, for example -- that function would be better named print_user_login_status() , or just print_login_status().



Code Layout

Always include the braces: This is another case of being too lazy to type 2 extra characters causing problems with code clarity. Even if the body of some construct is only one line long, do not drop the braces. Just don't.

   Examples:



		/* These are all wrong... In more than one way! */
		if (condition)	do_stuff();
		if (condition)
			do_stuff();
		while (condition) 
			do_stuff();
		for ($i = 0; $i < size; $i++)
			do_stuff($i);
		
		/* These are right. */
		if ( condition ) 
		{
			do_stuff ( );
		}
		while ( condition ) 
		{
			do_stuff ( );
		}
		for ( $i = 0; $i < size; $i++ ) 
		{
			do_stuff ( );
		}
	

Where to put the braces: This one is a bit of a holy war, but we're going to use a style that can be summed up in one sentence: Braces always go on their own line. The closing brace should also always be at the same column as the corresponding opening brace.

   Examples:


		if ( condition ) 
		{
			while ( condition2 )
			{
				...
			}
		}
		else 
		{
			...
		}

		for ( $i = 0; $i < $size; $i++ ) 
		{
			...
		}
		
		while ( condition ) 
		{
			...
		}
		
		function do_stuff( ) 
		{
			...
		}
	

Use spaces between tokens: This is another simple, easy step that helps keep code readable without much effort. Whenever you write an assignment, expression, etc.. Always leave one space between the tokens. Basically, write code as if it was English. Put spaces between variable names and operators. Put spaces just after an opening bracket and before a closing bracket. Put spaces just before a comma or a semicolon. This is best shown with a few examples.

   Examples:


		/* Each pair shows the wrong way followed by the right way. */
		
		$i=0;
		$i = 0;
		
		if($i<7) ...
		if ( $i < 7 ) ...
		
		if(($i < 7)&&($j > 8)) ...
		if ( ( $i < 7 ) && ( $j > 8 ) ) ...
		
		do_stuff( $i, "foo", $b );
		do_stuff ( $i, "foo", $b );
		
		for($i=0; $i<$size; $i++) ...
		for ( $i = 0; $i < $size; $i++ ) ... 
		
		$i=($j < $size)?0:1;
		$i = ( $j < $size ) ? 0 : 1;
	

Operator precedence: Do you know the exact precedence of all the operators in PHP? Neither do I. Don't guess. Always make it obvious by using brackets to force the precedence of an equation so you know what it does.

   Examples:


		/* what's the result? who knows. */
		$bool = ($i < 7 && $j > 8 || $k == 4);
		
		/* now you can be certain what I'm doing here. */
		$bool = ( ( $i < 7 ) && ( ( $j < 8 ) || ( $k == 4) ) )
		

SQL code layout: Since we'll all be using different editor settings, don't try to do anything complex like aligning columns in SQL code. Do, however, break statements onto their own lines. Here's a sample of how SQL code should look. Note where the lines break, the capitalization, and the use of brackets.

   Examples:


		SELECT *
		FROM table a, table b
		WHERE this = that
		AND this2 = that2
		

SQL insert statements: SQL INSERT statements can be written in two different ways. Either you specify explicitly the columns being inserted, or you rely on knowing the order of the columns in the database and do not specify them. We want to use the former approach, where it is explicitly stated whcih columns are being inserted. This means our application-level code will not depend on the order of the fields in the database, and will not be broken if we add additional fields (unless they're specified as NOT NULL, of course).

   Examples:


		# This is not what we want.
		INSERT INTO mytable (column1, column2, column3)	VALUES ('something', 1, 'else')
		
		# This is correct.
		INSERT INTO mytable
		(column1, column2, column3)
		VALUES
		('something', 1, 'else')
		



General Guidelines

Quoting strings: There are two different ways to quote strings in PHP - either with single quotes or with double quotes. The main difference is that the parser does variable interpolation in double-quoted strings, but not in single quoted strings. In this case, you should always use the double-quotes, just in case there is a variable. BUT if there is no text; there is only a variable, do not use quotes at all!

   Examples:


		/* wrong */
		$str = 'Blah, Blah, Blah';
		do_stuff("$str");
		
		/* right */
		$blah = "Blah";
		$str = "Blah, $blah, Blah";
		do_stuff($str);
		

Associative array keys: In PHP, it's legal to use a literal string as a key to an associative array without quoting that string. We don't want to do this -- the string should always be quoted to avoid confusion. Note that this is only when we're using a literal, not when we're using a variable.

   Examples:


		/* wrong */
		$foo = $assoc_array[blah];
		
		/* right */
		$foo = $assoc_array['blah'];
		

Comments: Each function should be preceded by a comment that tells a programmer everything they need to know to use that function. The meaning of every parameter, the expected input, and the output are required as a minimal comment. The function's behaviour in error conditions (and what those error conditions are) should also be present. Nobody should have to look at the actual source of a function in order to be able to call it with confidence in their own code.

In addition, commenting any tricky, obscure, or otherwise not-immediately-obvious code is clearly something we should be doing. Especially important to document are any assumptions your code makes, or preconditions for its proper operation. Any one of the developers should be able to look at any part of the application and figure out what's going on in a reasonable amount of time.

Magic numbers: Don't use them. Use named constants for any literal value other than obvious special cases. Basically, it's OK to check if an array has 0 elements by using the literal 0. It's not OK to assign some special meaning to a number and then use it everywhere as a literal. This hurts readability AND maintainability. Included in this guideline is that we should be using the constants TRUE and FALSE in place of the literals 1 and 0 -- even though they have the same values, it's more obvious what the actual logic is when you use the named constants.

Shortcut operators: The only shortcut operators that cause readability problems are the shortcut increment ($i++) and decrement ($j--) operators. These operators should not be used as part of an expression. They can, however, be used on their own line. Using them in expressions is just not worth the headaches when debugging.

   Examples:


		/* wrong */
		$array[++$i] = $j;
		$array[$i++] = $k;
		
		
		/* right */
		$i++;
		$array[$i] = $j;
		
		$array[$i] = $k;
		$i++;
		

Inline conditionals: Inline conditionals should only be used to do very simple things. Preferably, they will only be used to do assignments, and not for function calls or anything complex at all. They can be harmful to readability if used incorrectly, so don't fall in love with saving typing by using them.

   Examples:


		/* Bad place to use them */
		(($i < $size) && ($j > $size)) ? do_stuff($foo) : do_stuff($bar);
		
		
		/* OK place to use them */
		$min = ($i < $j) ? $i : $j;
		

Don't use uninitialized variables. The use of an uninitialized variable will usually be reported as an error. This will come up most often when checking which HTML form variables were passed. These errors can be avoided by using the built-in isset() function to check whether a variable has been set.

   Examples:


		/* Old way */
		if ($forum) ...
		
		
		/* New way */
		if (isset($forum)) ...