Clean Code: The Good, the Bad and the Ugly
Writing code is often a time-consuming task, but keeping things clean and in order can save some valuable time down the road for you and anybody else digging through your files. Clean code should be readable, lean and commented appropriately. Here are a few recommendations.
Include Comments
Comment your code. Your coworkers don’t want to read every line of your code to figure out what’s going on, and chances are neither do you. Comments should be concise, but need to explain how various parts of your code function. A lack of proper comments can turn a 10-minute task into a 30-minute task, so invest the time to document your work the first time around.
Omit Needless Code
If you find yourself using the same repeating piece of code throughout your project then you should consider consolidating. Write a function that you can call as many times as you need or create an “include” that you can embed in your templates.
Be Descriptive
Don’t be vague with your naming conventions when it comes to declaring variables or assigning classes and ID’s. For example, assigning a DIV with the class name of “div1” (<div class=”div1”>) will work exactly the same as assigning it with the class name of “search-form” (<div class=”search-form”>). However at first glance it’s clear that a DIV named “search-form” probably houses some type of search-related content – it’s far more descriptive and increases the readability of your code.
Separation of Content, Styles and Scripts
HTML helps structure the content of your site, while CSS helps style and lay out the way your site appears when viewing it in a browser. Keeping content separate from styles is a rule of thumb when developing on the Web. Not only should inline styles be avoided, but they’re frowned upon and your fellow developers will silently judge you if you use them. The same holds true for scripts – keep them out of your code and link to them externally.
Don’t Paste from Word
Don’t do it. Period. Documents created in Word are marked up with all kinds of proprietary Microsoft styles that will be embedded in your code if you copy and paste directly from a Word document to your HTML page. It’s ugly and it breaks validation. A safe way around this is to copy your text from Word and paste it in a text editor like Notepad first.
Keeping your code clean will help you manage it in the future, and it shouldn’t be an afterthought. I recommend validating during the development process to make sure you’re on the right track and using something like HTML Tidy, which is great for cleaning up your source code and making it more legible.
Let's get the discussion going. Please comment on this article.
