In any given week I can expect to write at least a few hundred lines of code in around four different languages. I can also expect to edit, review, and collaborate on code written by the other developers I work with.
Simply put, there’s a lot of code flying all over the place, and things can get very complicated when it’s not organized, managed, and most importantly, written well. Let’s look at a few different ways to improve the overall quality of our code.
Start Building Modules
One of the best ways to keep code consistent, reusable, and organized, is to group functionality together. For example, rather than dumping all your JavaScript into one main.js file, consider grouping it into separate files based on functionality, then concatenating them once you reach your build step. Of course, there’s a lot more to writing modular code, and you can write modular code for more than just JavaScript.
CSS preprocessors like Sass (our introduction here) allow you to write individual CSS files, and then include them into one main file when you compile them. This lets you write individual css files for different components like buttons, lists, and fonts. At the end, they’re all included into one main file, but maintaining these files becomes a whole lot easier. Here’s a look at how SitePoint author Hugo Giraudel organizes his Sass projects, and his favorite tools for doing so.
New technologies, such as Polymer allow you to write custom HTML elements, so that your HTML, CSS, and javascript can be grouped into individual components based on functionality. Be sure too look into Browserify (our introduction here), which allows you to use Node.js-style modules in the browser.
Or, if you’d prefer a video, here’s an introduction to the most common preprocessors for CSS, HTML and JavaScript: Sass, Haml and CoffeeScript.
Brad Frost also gives a great overview on the ideas and methodologies for writing modular code here.
Continue reading %6 Tips for Writing Better Code%