Writing Code - Keep it clean

April 21st, 2007 · Filed under Archives

Besides keeping your code organized, the code also should be clean.

There are several explanations to what clean code is. To me clean code is code that is not cluttered with unnecessary tags, functions and bits of code. In modern day tableless design environment a lot of tags can be styled so other tags are not necessary.

To create a section with a bold, italic, orange title, with grayish content, aligned to center, with a line at the end of the section, you could do it like this:
<div><p><font color="#FF9900"><strong><em>This is the subtitle of this section</em></strong></font></p>
<div align="center"><font color="#666666"><p>This is the content of this section. It is aligned to the center, because I want it to look like that because I think it's beautiful.</p></font></div>
<hr />
</div>

But there’s a cleaner way to get this done:

<div class="my_section">
  <p class="my_section_title">This is the subtitle of this section</p>
  <p>This is the content of this section. It is aligned to the center, because I want it to look like that because I think it's beautiful.</p>
</div>

And then you style this section in your stylesheet:

.my_section {
  color: #666666;
  text-align: center;
  border-bottom: 1 px solid;
}

.my_section p.my_section_title {
  color: #FF9900;
  font-weight: bold;
  font-style: italic;
  text-align: left;
}


Isn’t that more code?
Well, you do type a little more the first time. But working this way has several benefits:

  1. Your code is structural code (HTML) is separated from your styling code (CSS) which makes both clean.
  2. When you have several sections, you don’t need to add the styling code to the HTML of each one of these section. Just add the class and it will adapt to the appropriate styles.
  3. With 20 sections, changing the color of the head to a lighter shade of orange would simply mean changing 1 line in your CSS. In the other case you would need to change that 20 times.
  4. Search engines love not to have to go through all kinds of cluttering (styling) code to find your content.

Programming
The same principles can be used in programming and scripting. Instead of repeating a certain action, you can create a function with the action to be taken, and call this function where you need these actions taken.

I made it a habit to create a file called functions.php where I store all my functions, and I include this file everywhere I need those actions defined in my functions. The same with database information, styling, constants, etc.

Conclusion
Clean code will save you and your visitors time. It’s easier to make changes when your code is clean and organized. And the less clutter a web server has to go through to be able to display the content, the faster the page will be displayed. Plus, search engines will love you more.


blog comments powered by Disqus