Every developer will need to maintain code that is not his or her own at one point or another. Nothing makes a developer happier than working with a clean well laid-out template file. If someone else may one day be taking over what you’re working on, you should always strive to write better code and keep your templates as clean and elegant as possible.
In this post I’ll go over some general do’s and don’ts to follow that can help ensure your code is clean.
1: Use Minimal Markup.
Don’t get carried away with throwing classes on everything or nesting more <div>s than you need to. The less markup you have in your template the easier it is to make changes to what’s already there.
A vague possibility of a very specific use case or a they may want to bring it back down the line isn’t a good enough justification for leaving blocks of HTML commented out using php comments, or worse, html comments. If you’re a developer or company worth one’s salt, your entire code base will be versioned. Should you need to revert or bring back old functionality, you can go back to old copies of the file and bring over what is needed. Using clever commit messages can help you in this regard when deciding to clean up a template.
3: Inline conditional statements are your friends
Don’t be scared. Inline conditional statements are perfectly fine to use and can help you significantly cut down on extra unnecessary markup. Here is a very basic example.
This is the most important and useful thing you can do. I often find myself asking others for opinions on code I write, and I almost always receive fantastic feedback on how I can improve it. Peer reviews benefit both parties involved. Each person can offer insight on how they may have went about solving a problem, or how the existing solution could be improved (even if only slightly).
6: The other side of the template – Be smart about your CSS
With CSS frameworks like SASS and LESS, it can be easy to get carried away making maintaining your template harder. Use the absolutely bare minimum of nesting when styling classes and elements. You don’t want to be the the person to throw an important tag on something because you don’t want to have to navigate through a tree of selectors just to change the colour of the paragraph text.
Those are some of the basics that I believe everyone should follow when writing code. Sticking to those as a starting point and thinking of some general convention to follow will help ensure your templates are squeaky clean and easy for anyone to modify.