Writing code – Keep it organized
April 10th, 2007 · Filed under ArchivesWhen 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.
Trackback URL for this post:
http://rehuel.com/2007/04/10/writing-code-keep-it-organized/trackback/




