Class Names: Coding Standards

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 7

Coding Standards

Class Names
 Use upper case letters as word separators, lower case for the rest of a word
 First character in a name is upper case
 No underbars ('_')

Justification
 Of all the different naming strategies many people found this one the best compromise.

Example
class NameOneTwo
class Name

No All Upper Case Abbreviations


 When confronted with a situation where you could use an all upper case abbreviation instead use an
initial upper case letter followed by all lower case letters. No matter what.

Do use: GetHtmlStatistic.
Do not use: GetHTMLStatistic.

Variable Names
 use all lower case letters
 use '_' as the word separator.

Example
function HandleError($errorNumber)
{
$error = new OsError;
$time_of_error = $error->GetTimeOfError();
$error_processor = $error->GetErrorProcessor();
}

Array Element
Array element names follow the same rules as a variable.
 use '_' as the word separator.
 don't use '-' as the word separator

Justification
 if '-' is used as a word separator it will generate warnings used with magic quotes.

Example
$myarr['foo_bar'] = 'Hello';
print "$myarr[foo_bar] world"; // will output: Hello world
$myarr['foo-bar'] = 'Hello';
print "$myarr[foo-bar] world"; // warning message

Function Names
 For PHP functions use the C GNU convention of all lower case letters with '_' as the word delimiter.

Justification
 It makes functions very different from any class related names.

Example
function some_bloody_function()
{
}

No spaces should be given while passing parameters


eg. get_user_data($username, $password); // correct

Braces {} Policy
Of the three major brace placement strategies two are acceptable, with the first one listed being preferable:
 Place brace under and inline with keywords:
if ($condition) while ($condition)
{ {
... ...
} }

 Traditional Unix policy of placing the initial brace on the same line as the keyword and the trailing
brace inline on its own line with the keyword:
if ($condition) { while ($condition) {
... ...
} }

Indentation/Tabs/Space Policy
 Indent using 2 spaces for each level.
 Do not use tabs, use spaces. Most editors can substitute spaces for tabs.

Example
function func()
{
if (something bad)
{
if (another thing bad)
{
while (more input)
{
}
}
}
}

The PEAR RFC standard calls for 4 spaces, not tabs of any size, in your code. I disagree with
this personally and will continue to tab my code. Tabs rather than spaces will create smaller
files and smaller files are faster to parse, upload, download, etc etc. The other advantage to
using tabs is that you can set your tab size to your personal preference when viewing someone
else's code. I used to use 8-space tabs, but recently switched to 4-space tabs and all my code
"reformatted" automatically by just setting a preference in vim.

Parens () with Key Words and Functions Policy


 Do not put parens next to keywords. Put a space between.
 Do put parens next to function names.
 Do not use parens in return statements when it's not necessary.

Justification
 Keywords are not functions. By putting parens next to keywords keywords and function names are
made to look alike.

Example
if (condition)
{
}

while (condition)
{
}

strcmp($s, $s1);

return 1;

Condition Format
Always put the constant on the left hand side of an equality/inequality comparison. For example:
if ( 6 == $errorNum ) ...
One reason is that if you leave out one of the = signs, the parser will find the error for you. A second reason
is that it puts the value you are looking for right up front where you can find it instead of buried at the end of
your expression. It takes a little time to get used to this format, but then it really gets useful.

Single or Double Quotes


 Access an array's elements with single or double quotes.
 Don't use quotes within magic quotes

Justification
 Some PHP configurations will output warnings if arrays are used without quotes except when used
within magic quotes

Example
$myarr['foo_bar'] = 'Hello';
$element_name = 'foo_bar';
print "$myarr[foo_bar] world"; // will output: Hello world
print "$myarr[$element_name] world"; // will output: Hello world
print "$myarr['$element_name'] world"; // parse error
print "$myarr["$element_name"] world"; // parse error

Global Variables
 Global variables should be prepended with a 'g'.
Justification
 It's important to know the scope of a variable.

Example
global $gLog;
global &$grLog;

Define Names / Global Constants


 Global constants should be all caps with '_' separators.

Justification
It's tradition for global constants to named this way. You must be careful to not conflict with other predefined
globals.

Example
define("A_GLOBAL_CONSTANT", "Hello world!");

Static Variables
 Static variables may be prepended with 's'.

Justification
 It's important to know the scope of a variable.

Example
function test()
{
static $msStatus = 0;
}

Document Null Statements


Always document a null body for a for or while statement so that it is clear that the null body is intentional
and not missing code.

while ($dest++ = $src++)


; // VOID

Use if (0) to Comment Out Code Blocks


Sometimes large blocks of code need to be commented out for testing. The easiest way to do this is with an
if (0) block:
function example()
{
great looking code

if (0) {
lots of code
}

more code
}

You can't use /**/ style comments because comments can't contain comments and surely a large block of
your code will contain a comment, won't it?

*Notes

1) Img tag should always have “alt” attribute.


2) session_start() function should always be place on the second line
eg.

<?php
session_start();
//my code
?>

3) Avoid repetition of &nbsp; for adding spaces


Use padding ( top, right, bottom, left ) / letter-spacing / word-spacing instead of it.

eg.

<span style="padding-left:20px">This line starts after some blank space at left</span>


OR
<span style="font:Arial; font-size:larger; word-spacing 10px;">This is some text.</span>

4) Use mysql_close() to close every mysql connection you make

5) Use label tags instead of directly giving the names for text boxes
eg.

Firstname: <input type = "text" name = "firstname"> // Incorrect

<label for=”firstname”>Name</label> // Correct


<input type="text" name=”fname” id="firstname" />

Reason:
When u click on label tags, they autofocus on textbox, which helps mouse users in navigation.

6) require_once() is expensive in terms of memory

7) Write Long SQL Queries as :


$sql="SELECT id, name FROM people"
."WHERE name ='test'"
."OR name='abc'"
."ORDER BY name ASC";
."LIMIT 20";

8) Single quotes vs Double quotes


' I\'ll complete it '
“ I'll complete it ”

Backslashes interpreted inside “ ” only

' My C:\\*? drive ' ~ ' My C:\*? drive '

Variables dont expand in ''

' My variable is $var ' ~ My variable is $var

echo "A banana is {$fruits['banana']}.";


9) Use error_reporting(E_ALL) to show all errors
Use it only at the time of coding.

10) If you need to find out the time when the script started executing, $_SERVER[“REQUEST_TIME”] is
preferred to time()

Some more coding standards that can be implemented

11) SQL Injection :

$query = "SELECT *
FROM users
WHERE name = '{$_GET['name']}'";
In this case, the value of $_GET['name'] is provided by another source, the user, but it is neither filtered nor
escaped.
Escaping preserves data in a new context. The emphasis on escaping output is a reminder that data used
outside of your Web app needs to be escaped, else it might be misinterpreted.
Assuming we're using MySQL, the SQL injection vulnerability can be mitigated by escaping the name with
mysql_real_escape_string(). The following example demonstrates filtering input and escaping output, with
naming conventions used for code clarity:
// Initialize arrays for filtered and escaped data, respectively.
$clean = array();
$sql = array();
// Filter the name. (For simplicity, we require alphabetic names.)
if (ctype_alpha($_GET['name'])) {
$clean['name'] = $_GET['name'];
} else {
// The name is invalid. Do something here.
}
// Escape the name.
$sql['name'] = mysql_real_escape_string($clean['name']);

// Construct the query.


$query = "SELECT *
FROM users WHERE name = '{$sql['name']}'";

More details can be read from :


http://www.goodphptutorials.com/out/Introduction_to_SQL_Injection

12) Use Ternary Operators :


$host = strlen($host) > 0 ? $host : htmlentities($host);

13) No short tags.


Always use the long PHP tags: <?php echo "hello world"; ?>
Do not use the echo shortcut <?=.

Do not use ASP like tags: <% echo "hello world"; %>

14) GPC magic quotes.


Include code in a global include file which is run before any $_GET or $_POST parameter or $_COOKIE
is read. That code should check if the gpc_magic_quotes option is enabled and run all $_GET, $_POST
and $_COOKIE values through the stripslashes function.
15) Have one single configuration file
You should define all configuration parameters of your application in a single (include) file. This way you can
easily exchange this file to reflect settings for your local development site, a test site and the customer's
production environment. Common configuration parameters are:

- Database connection parameters


- email addresses
- options
- debug and logging output switches
- application constants

16) Use Active Records for MySql queries

You might also like