2ndMay 2011

Code styles

Posted at 4:23pm by Jason in Code snippets,Web development

Tags: , ,

It may seem a little dull and mundane, but working with a consistent coding style will always benefit whatever project that you are working on. The style, or convention, that I’ll be outlining here is what I have come to use over a long period of time. It has also been honed by working with other developers, taking on new ideas and methods.

It is when you are working in a team that using a consistent coding style really pays off. It helps keep all the code clean and readable, therefore more maintainable in the long term. That has got to be a good thing.

The coding style that I try to stick to is not “the definitive” style, everyone will probably have their own, but it is something that I feel comfortable using on a daily basis. I try to also be consistent across the languages that I use on a daily basis, so I will tend to use the same conventions in JavaScript, CSS, HTML and PHP.

Pascal the Camel

Camel Case or Pascal Case – the great debate. Firstly what are they? They are both pretty similar in that compound words have a specific capitalisation, with the word boundaries being capitalised. With Camel Case, the first word is not capitalised.

thisIsAnExample

The name apparently stems from the capitals being likened to camel humps – seems reasonable to me. Pascal Case can be considered just a variant of Camel Case where the compound word also starts with a capital letter. In fact some people refer to it as Upper Camel Case. The name derives from the fact that this convention was popularised with the Pascal language (the first programming language I was actually taught, and I used a lot when churning out lots of Delphi applications in the early 2000’s).

ThisIsAnExample

Anyway, now that is cleared up, where are these used? All my variable and function names are in Camel Case. In CSS, I also use Camel Case for class names. For OOP classes and IDs in CSS I will use Pascal Case.

class MyNewClass extends BaseClass {
  private $varOne;
  private $varTwo;
 
  public function myClassMethod(){
    //some code here...
  }
}

<div id="Content" class="productDetails"> . . . </div>

Braces and indentation

Everything I do every day involves braces (curly brackets), and indentation. Only the braces are actually required, but a standard approach to indentation just makes everything so much easier to read.

My approach to how I use braces has changed over the years as I switch between various languages. The last code example gives you an idea of how I use them now, but I started off by always having opening braces on a separate line, with the contents of the containing code block being indented.

function oldStyleBraces()
{
  //this is some code
}

Now, however I prefer the opening brace on the same line as the start of the code block definition. This goes for Classes, functions/methods and practically every other code block (if/while/for/foreach etc.). With CSS, this is also the case with the opening brace being on the same line as the selector

#Content {
  float: right;
}

With indentation I prefer to use tab spacing. This means that others working on the same project can control the indentation size to match their own preferences by tweaking the tab size in their preferred IDE. I tend to use the setting 1 tab = 2 spaces.

function fullExample($someVar = false){
  $result = false;
  if($someVar){
    //do some stuff
    $result = someOtherFunction();
  }
  return $result;
}

Spaces

Related to indentation and just making your code easier to read, I use spaces quite liberally. I find it really does make a difference if spaces are added between operators and operands. I don’t add spaces between an opening or closing bracket and the closest variable.

$result = $varOne + $varTwo;
 
$str .= 'This is one string' . $anotherString;
 
$result = someFunction($param1, $param2, $param3);

There is an argument to be had that this introduces file bloat and therefore can slow stuff down, particularly in the case of JS and CSS files. Well, I would rather have a maintainable code base and use some of the multitude of minification tools out there to compress the source (removing extra white space and comments etc.) in the production environment than write code that way in the first place.

Initialisation

Try to initialise all your variables with some known value before your use them, unless of course the first time you use the variable is actually an assignment from some other process. This just means you know where you are and if some decision results in the variable not being assigned a value, then at least you have a meaningful value already there. With PHP you also avoid the many unnecessary notices about variables that don’t exist. Of course you disable those in the production environment, but not having them in the first place is much better.

With this in mind, in functions/methods that will ultimately return a value, I always initialise the return value and to enforce that I try only to have one return statement in the function.

NO:function someFunction($param1){
  if($param1){
    return true;
  } else {
    return false;
  }
}

YES:function someFunction($param1){
  $result = false;
  if($param1){
    $result = true;
  }
  return $result;
}

Obviously the above are just illustrations so please don’t get on my back about inefficient coding…

Passing comment

Comments are good. End of. Ok, you can have too much of a good thing, with comments drowning the code, but having no comments is much worse. In collaborative environments it shows your colleagues (or future code maintainers), what you were thinking and why you did something that way. If you are working by yourself, then they will serve as memory joggers. If you return to a project after 6 months to a year, you may not quite remember what you were doing and this will provide a kick start.

In PHP there are several ways of adding comments and I use 3 on a regular basis.

Multiline comments are defined with /* and */ and anything in-between is treated as a comment, including new lines. I use these when I am prototyping and have created stub functions/methods and I outline what I intend to do. Most IDEs will helpfully close multiline comments for you and also embellish them with some extra * at the start of each line, just to make them look nice.

/* This is a multiline comment on a single line */
 
/* This is a multiline comment
that extends over several lines and
is quite long */
 
/*
* This is a multiline comment
* that extends over several lines and
* is quite long
*/

Of course, using this method doesn’t have to extend across multiple lines and is very handy for temporarily commenting out sections of code within the same line. However, if the comment is quite short then the single line comment should be used. There are two variants and I only use one.

# this is a single line comment.
 
// this is a single line comment. I use this format.

I try and keep single line comments short. If I find I am using several single line comments in a row, I’ll switch it to a multiline comment.

The 3rd type of comment is a variant on the mutliline. PHPDoc is a method of documenting your code inline. A PHPDoc parser can take your code and pull out all the PHPDoc blocks to create HTML formatted documentation. Some IDEs like, you’ve guessed it, Eclipse can also pick this up to provide more information for code completion and outlining. Notice that a PHPDoc block is opened with /** rather than /*.

/**
 * This is some description of a class method.
 * It does this and this and that and is
 * very clever
 * @access public
 * @param string $param1
 * @param boolean $param2
 * @return boolean
 */
public function someMethod($param1, $param2 = false){
  //some code here...
}

Much more information can be added to the PHPDoc comment block. I don’t use if fully and is an area I really need to improve. More info can be found on the PHPDoc site.

I try to include a PHPDoc comment block for every function/method and class declaration.

PHP strings

There are some areas of PHP where I try and maintain a consistent approach and string handling is one. There are several ways to represent strings in PHP – single quoted strings, double quoted strings and HereDoc syntax. Now in PHP 5.3 there is the NowDoc syntax too.

For just a standard string I will tend to use single quotes. All text within a single quoted string is rendered as is and no special processing takes place. Single quotes need to be escaped, but double quotes do not.

If I need to add in some data from either a variable or a method (not function) call, I will then use the double quoted syntax where variables are expanded and escape sequences (such as \n for a new line) are processed. Just to keep things clear I will enclose any variable or method call in braces within the string. Double quotes need to be escaped with a backslash, but single quotes don’t.

With Heredoc, you get variable expansion etc. but you don’t have the hassle of having to escape quotes – very handy.

$str = 'This is a single quoted string';
 
$str = 'This is a single quoted string created at ' . date('Y-M-d H:i:s);
 
$str = "This is a double quoted string including the \$param1 variable: {$param1}\nThis is a new line";
 
$str = "This is a double quoted string created at {$ob->currentTime()}";
 
$str = <<<ENDOFTEXT
This is a heredoc string created at {$ob->currentTime()} and
new lines do not require escape sequences and " and ' don't need
to be escaped.
ENDOFTEXT;

Switch and fall through

The Switch statement is a great alternative to multiple if statements and make much clearer reading. You can also have several cases execute the same piece of code by allowing one case statement to fall through to the next one. Adding in a single line comment indicating that this is what is happening means the intention is clear and it won’t be mistaken for a bug where a break statement at the end of the case was omitted accidentally. Been there, done it, had the unnecessary debugging time.

Switch($var){
case 'this':
$result = false;
break;
case 'that':
//fall through
case 'other':
//fall through
default:
$result = true;
break;
}

It is simple and can save a lot of time later on.

EOF

Well, I think that is enough for the time being. Coming soon to a screen near you will be my take on database schemas.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.