Jun 11, 2010

Posted by in PHP, Technology | 0 comments

Good Code VS Bad Code

My experience and 3rd party modules and coding structure inspired me to write this blog. Evey beginner writes junk code (TRUE), I did that when I was a newbie. But, this can be avoided with proper guidance and by remembering certain coding styling techniques.

You write damm bad code but if your code is indented properly, it will be treated as a nice code, as every body can read that, and rectify and guide you in your mistake. If you will write a very nice (SUPERB) – 10 out of 10 (RATING) kinda code but with out doing any coding indentation, that will surely be treated as a JUNK, people will try to modify your code, rather then getting inspired from your code.

So lets follow few simple steps to keep our code neat and clean. Very simple steps not much really.

Before writing the steps let's consider the following example.

BAD CODE

<div id="mainmenu">
<div class="content">
<ul id="navmenu">
<li>Link1</li><li>Link2</li></ul>
</div><div class="header">My header
</div>
</div>

This is a very small piece of code, but still it will take time for you to make out the starting and ending tags, if you would like to insert any thing in between, it will take more time for you. Consider a long html file, a template file with this kind of code, how difficult it is to make any change it that.

Now lets consider the same code written neatly

Good Code

 

<div id="mainmenu">

  <div class="content">
     <ul id="navmenu">
           <li>Link1</li>
           <li>Link2</li>
     </ul>
  </div><!– eof #navmenu –>

  <div class="header">
      My header
  </div><!– eof #header –>

</div><!– EOF #mainmenu –>

Same code is written with proper comment and indentation which is a bit clear to understand.

Tips for writing good code

1. After every end tag, closing braces "}" put a comment and state its ending related to parent tag.

eg. 

var $num = $_REQUEST['num'];

if($num > 20)
{

   echo "Invalid Number";

}//eof if($num > 20) Important when your if block has a lots of code.
else
{
  echo "Valid Number"
}
Do consider the above HTML code where I have commented the end of HTML tags properly.

2.  Always use a tab for each new block of code. Better the indentation, nicer the code.

See the indentation in previous examples.

There are other guidelines to follow too, but simple if we follow these two magic rule, our code will look much better and will be easy to read and understand.

Thanks for your interest. Do you have any better suggestion ?? Comment it, and I will include it in my post.

Leave a Reply