Writing code – Keep it organized

April 10th, 2007 · Filed under Archives

When writing any type of code, whether it’s HTML, PHP, Perl or some other kind of programming language, it is important to write neatly.

In most programming and scripting language it doesn’t matter if you write all the code on one line. The code is then read just like we humans read, from left to right, with the necessary jumps here and there to find the right functions.

There are several reasons why you want to avoid writing too much code bundles together on one line:

  • Code is easier to debug if it is neatly organized
  • Organized code is easier to reuse
  • Code is easier to read for others (in case of sharing the code or asking for help)
  • Well organized code looks great and professional

Best practices
Indent nested code
Add one or 2 spaces, or a tab to parts that belong to a parent section.
Example 1: HTML

<div id=”1″>
  <div id=”2″>
    <p>This is the text that belongs in div 2, which is nested within div 1</p>
  </div>
</div>

Example 2: CSS

#1 {
  color: #FFFFFF;
  font-weight: bold;
}

Example 3: PHP

while($result = mysql_fetch_object($query)) {
  if ($result->type == “5″) {
    echo “You are not allowed to see this resource!”;
  }
  echo “This is type ” . $result->type . “.”;
}

Add an empty line between sections
If you have a function handling a query and after that you have a definition of a function to handle the output to the website, add a blank line so you can see where that particular section starts and ends.

Use standards
The modern day standards for HTML and CSS say that uppercase tags and attributes are replaced by lowercase code. <BODY> is now simply <body>.
For accessibility reasons, some tags are being replaced by others: <b> is replaced by <strong>, <i> is replaced by <em>.

Conclusion
Keeping your code organized is not only a good practice for yourself (reusibility, debugging), but also for others, who’s help you might need or who you shared your code with.

Another tip: Keep your feeds organized and add mine to your list.


  • http://www.techrivet.com Greg O’Byrne

    I find the php bracketing less easy to read then the braketing formatting I’m used to using in C# which has the opening bracket follow on the next line like so.

    function foo(string PassingIn)
    {
      //do something to PassingIn;

      return PassingIn;
    }

    Much clearer. Well to me anyways, besides that you are absolutely right.

  • http://www.rehuel.com Rehuël

    Yes, that’s a way to do it too. Personally I prefer the method mentioned in the post, but your suggestion is also very good and clear.

blog comments powered by Disqus