10 Principles for Keeping Your Programming Code Clean

10 Principles for Keeping Your Programming Code Clean

A common issue in almost every profession that can drive people completely insane is having to continue from what somebody else started. The main reason for this being the fact that everyone has different ways of working, and sometimes these self-induced habits can be just downright messy.

In order to make code look cleaner, and thus, support team work (meaning that somebody else might need to work with what was coded before), there are certain considerations that should be taken into account.

10 Principles for Keeping Your Programming Code Clean

Keeping Your Programming Code Clean

1. Revise Your Logic Before Coding

Before blindly typing into the debugger of choice, some flow diagrams or written pseudo-code might come in handy to previously verify the logic behind those lines of code. Writing it down first can clarify many doubts or insecurities about complex functionality, and therefore save a lot of time. But most importantly, helping you get it right faster will also help you avoid all the messy code replacements and additions that tamper with the following principles.

Revise Your Logic Before Coding

2. Clearly Expose the Structure of the Page

Working with main containers is useful, but working with main containers with a representative ID is even more useful. Consider the following starting scenario:

        <div id="main-container">
            <div id="header">
                <div id="logo">...</div>
                <div id="main-menu">...</div>
            <div id="content">
                <div id="left-column">...</div>

                <div id="center-column">...</div>
                <div id="right-column">...</div>
            <div id="footer">
                <div id="footer-menu">...</div>
                <div id="disclaimer">...</div>

The structure appears evident, thanks to the DIV containers that are concretely named after their destined content. Not only will it be simpler to start adding code, but it’ll also be perfectly transparent for someone who tries to add or remove something afterward. This structuring method, however, should be aided by the next statement.

3. Use the Correct Indentation

Supporting the previous pronouncement on structure, indentation distinctly displays the opening and closing points of each element used. If every line of code is glued to the left side of the screen, it’ll be very hard to distinguish the exact place where an element is closed. Therefore, it’ll mess up the effort made at designing a complete structure, since it won’t be noticeable afterward.

Use the Correct Indentation

4. Write Explanatory Comments

Underestimating the value of good comments is disregarding a very effective way of code documentation. It’s easy, fast, and very straight-to-the-point, since it’s done right then and there when it’s needed.

Comments are also efficient considering the fact that they can be read at the exact moment of doubt. They can, however, be overused. And that brings us to the next recommendation.

5. Avoid Abusing Comments

Comments aren’t to be treated lightly. When commenting on code, the current functionality is explained in terms of variables and results. What comments are NOT made for is:

  • Writing explanatory notes to self (e.g. /* Will finish this later… */).
  • Blaming stuff on other people (e.g. /* John coded this. Ask him. */).
  • Writing vague statements (e.g. /* This is another math function. */).
  • Erasing chunks of code. Sometimes people are not sure of erasing things and it’s not absolutely evil to comment that code instead.

What’s not right is to just leave it afterwards. It’ll be terribly confusing. If the code will be documented via embedded comments, the team members need to make sure those comments are there for a reason.

Examples of good comment use are:

  • Authoring specifications (e.g. /* Coded by John, November 13th 2010 */).
  • Detailed statements on the functionality of a method or procedure (e.g. /* This function validates the login form with the aid of the e-mail check function */).
  • Quick notifications or labels that state where a recent change was made (e.g. /* Added e-mail validation procedure */).

Avoid Abusing Comments

6. Avoid Extremely Large Functions

In the process of adding functionality to an application, its coded methods tend to grow accordingly. One can come across functions that consist of up to a hundred lines of code, and this tends to become confusing.

A better practice would be to break up large functions into smaller ones. Some procedures may even be repeating themselves amongst the rest of the functions conforming the whole application process. The team could make better use of those repeated procedures through separate functions. This, however, should have been avoided from the beginning if the first recommendation was carried out correctly.

7. Use Naming Standards for Functions and Variables

Whenever a variable or a function is created, its name should be descriptive enough as to give a general idea of what it does or what it’s for.

Use Naming Standards for Functions and Variables

There are companies that have their own pre-established naming standards (e.g. The prefix ‘int_’ for any numeric variables), but there are also many companies in which the employees do not keep these standards. Laziness makes people work double the time during future redesigns, so everyone needs to start learning how to get rid of it.

8. Treat Changes with Caution

The correct appliance of changes summarizes a lot of what has been previously said, like commenting meaningfully and not disrupting indentations. Nevertheless, it needs to be emphasized. Whenever there’s a need for adding, removing, or changing something, there should also be an awareness of not meddling with previous efforts for maintaining the code clean and ordered.

This mainly involves:

  • Keeping the correct indentations (e.g. when inserting an IF clause, its contents’ indentations will be augmented).
  • Commenting on the modification made or broadening the existing comments.
  • Respecting standards in use.

9. Avoid Indiscriminate Mixing of Coding Languages

In-line CSS styling and scattered JavaScript tags with short procedures within them are very good examples of incorrect mixing of coding languages throughout your development process. Ignoring this principle will result in huge element tags with an embedded STYLE property, lots of interruptions in the flow of the structure because of embedded functions, and of course lots and lots of confusion.

Avoid Indiscriminate Mixing of Coding Languages

Even with the addition of comments, it’ll still look like everything and nothing at the same time. Having the appropriate divisions between different coding languages will give order to the logic applied. This brings us, though, to the next consideration.

10. Summarize Your Imports

Even though it is much better to have additional coding languages imported from different files, this shouldn’t be abused. If there are too many style sheets, they can probably be summarized into one or two.

This won’t only save space and make things look cleaner, but it will also save loading time. Each imported file is an HTTP request that tampers with the performance of your application. So apart from being a consideration for tidiness, it is also a consideration for efficiency.

And, of course, this way one can avoid dealing with Internet Explorer’s limit to the number of individual stylesheets.

To Sum Up

What’s convenient isn’t always what’s best for the development process, since finding the convenient way to do something tends to drive us towards disregarding coding efficiency. Implied in this case for efficiency, there is a high need to keep up with standards in order to maintain a code that’s readable in the future. Considering that it won’t always be the same person who works on upgrading the same application, code should be sufficiently open and understandable for it to really support team work.

Pamela Rodríguez Domínguez is Mobile Interface Designer at Naranya AppHouse, with a burning passion for writing and reading. She loves studying new things on her free time, along with giving conferences and undergraduate classes on web and mobile related subjects. Even though she is an engineer at heart, she has the soul of a writer with a bit of an artistic touch.


  1. / Reply

    Great article, Pamela. I have been looking for software (Mac) for creating such flow diagrams. Can you recommend any or do you use pen and paper? I sometimes use Mindnode to create mindmaps, but Mindnode is not really tailored for this job.

    1. / Reply

      Thanks! I’m an old fashioned pen and paper user, but there are a lot of good online tools you can use, like Gliffy (http://www.gliffy.com/). For Mac particularily, though, I think you can use Omnigraffle. I’m not a Mac user, but I’ve seen it used for that purpose, too.

    • Casey,
    • January 20, 2011
    / Reply

    Great article, always looking for ideas for cleaner code. For me instead of naming structural code “right-col” or “left-col” I like to give them names like “primary-col” and “secondary-col” so if the CSS happens to change from a right column layout to a left one the underlying HTML still makes sense.

    1. / Reply

      Thank you, Casey. And it is a good point on the column names, I’ll consider it in the future.

  2. / Reply

    I enjoyed this article, having to deal with messy code is never fun. I can’t say I do a lot of flow diagrams before coding, but writing unit tests before coding really helps with program logic.
    Some languages such as Python use indentation for defining blocks instead of curly braces which Javascript uses, Python then can only run if the correct indentation is used. This idea has been used with SASS and HAML, producing beautifully indented code and output such as HTML.

    When it comes to beautiful Javascript there is JSLint which is a great tool for validating JavaScript, as well as making sure that tabs and spaces have not been mixed for indentation.
    Company naming standards for variables is a tricky one, it can be helpful but a down right pain to remember and refactor. I personally like short variable names with underscores while another developer might like long variable names in camel case. Some programming languages have naming conventions built in such as Ruby, using uppercase for class names and using @ for instance variables for example.

    If you are using a version control system such as cvs, svn or git, when commiting don’t put what you have commited, but instead put why you have commited. For example: “removed code” is a bad commit message, instead “fixed problem with user login not working” describes why you have removed code.

    Thanks again for the article Pam

    1. / Reply

      I know what you mean about the company standards for variable names, and that becomes a great pain when they make you use long prefixes like [variable type]_[function]_[name]. It should be something shorter like you said, more on the lines of ‘str’ before the name of a string variable.

      And I have worked with version control systems so I hear what you say about comments on that regard. Good observation.

      I’m glad you enjoyed the article.

  3. / Reply

    It is very true that self-induced habits get in the way over time. Thanks for this informative article Pam; it has nudged me to stay on the ‘straight’ path of clean coding.

  4. / Reply

    great advise i was having trouble with this type of stuff since im a designer first and programmer second but with these steps i think i shouldn’t have to many more problems from this


  5. / Reply

    Great article on keeping code clean. I always upload the optimized version and keep the marked up code behind ready to use in DW. Thanks for some great tips.

    • Rana Mukherjee,
    • January 21, 2011
    / Reply

    Good article.I remember..

  6. / Reply

    Really this is a great blog you have provided so many tricks to get cleaner code after reading this blog i will try to follow these techniques but problem is that i will follow this other will not follow then i have to waste time in understand their code.

    1. / Reply

      I know, that makes it harder. I think we also need to make others in our team aware of the benefits of clean coding, because they will have to deal with other people’s code themselves.

      Good luck and thanks for reading!

  7. / Reply

    A great article on clean coding. It is so easy to get carried away when coding then when you come back to it to change the smallest thing you can’t find the relevant section. Some great tips you have given, will definitely be bookmarking this page.

  8. / Reply

    Now if we can get people to actually write code this way. I have gone behind a lot of people and found code that was barely recognizable much less organized. CSS spread all over the place with header code under footer code or header code in fifty different places.

    It’s so bad I usually won’t clean up anyone else’s mess anymore. I’ll offer a new site with new code or recommend someone else. It’s not worth the money to me.

    1. / Reply

      I understand that, and I’ve been there. Once a project is too far into the development process, it’s not an easy or even a possible task to correct what has been done wrong in what comes to coding standards.

      I do recommend, however, that you consider investing some time in recommendation #10, since it isn’t just for code maintenance purposes, but also for site load optimization, since each call to a stylesheet or a javascript archive slows down your performance.

  9. / Reply

    Read this book: Clean Code – Robert Martin

    1. / Reply

      I’ll look it up, thank you.

    • Graham Wilson,
    • January 22, 2011
    / Reply

    Nice and useful article. Well, like many have mentioned, how good it will be if programmers can remember these pointers next time when they code.

  10. / Reply

    Great article! Coding like this definitely makes it easier to read, understand, and edit later. The PHP and JavaScript snippets I’ve written and published on my website conform to this type of coding. http://artbyjb.com/code/

    • Ying,
    • January 23, 2011
    / Reply

    Good list of ways of cleaning up code. I like Eclipse’s auto formatting. The section of commenting is my favorite. Thank you for sharing.

    • Shane,
    • January 23, 2011
    / Reply

    Excellent article :) I myself are guilty of perpetrating practically all of the commenting related sins of coding.

    • Apie,
    • January 30, 2011
    / Reply

    Thanks for this useful info.. it remains a food for thought.

  11. / Reply

    If every line of code is glued to the left side of the screen, it’ll be very hard to distinguish the exact place where an element is closed. Therefore, it’ll mess up the effort made at designing a complete structure, since it won’t be noticeable afterward.

  12. / Reply

    I need some great hand-drawn for my new project. List was helpfull, so thanks a lot and kind regards from Germany

  13. / Reply

    Die Stahlseile, so dick wie Männerarme, werden dort in gigantische Maschinen eingespannt und dann mit gewaltiger Kraft so lange gespannt, bis sie mit einem entsetzlichen Schrei zerreißen. An diesen Besuch muss ich oft denken, wenn Designer sehe, die Feedback vom Kunden bekommen.

  14. / Reply

    so dock and dock2 both are different.. well will it be possible to have same id name..

  15. / Reply

    talented designers and artists that choose to provide beautiful and useful icon sets for commercial and/or personal usage.

  16. / Reply

    Thanks for this useful info.. it remains a food for thought.

    • ed,
    • July 28, 2012
    / Reply

    > Examples of good comment use are:

    > Authoring specifications (e.g. /* Coded by John, November 13th 2010 */).

    No, they are horrible clutter that is hurtful to any code base, has no value can creates crap people need to read again and again that has no value at all. Source control exists for decades and is used for exactly that purpose

    > Detailed statements on the functionality of a method or procedure (e.g. /* This function validates the login form with the aid of the e-mail check function */).

    Thats what function names and class names are for; If you can’t explain what it does in the name then it’s to complex. There are very very few cases where documenting a function is useful instead of obvious timewasteing clutter

    > Quick notifications or labels that state where a recent change was made (e.g. /* Added e-mail validation procedure */).

    We talked about source control already.. this is just to painful to endure

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Iconfinder Coupon Code and Review

Iconfinder offers over 1.5 million beautiful icons for creative professionals to use in websites, apps, and printed publications. Whatever your project, you’re sure to find an icon or icon…

WP Engine Coupon

Considered by many to be the best managed hosting for WordPress out there, WP Engine offers superior technology and customer support in order to keep your WordPress sites secure…

InMotion Hosting Coupon Code

InMotion Hosting has been a top rated CNET hosting company for over 14 years so you know you’ll be getting good service and won’t be risking your hosting company…

SiteGround Coupon: 60% OFF

SiteGround offers a number of hosting solutions and services for including shared hosting, cloud hosting, dedicated servers, reseller hosting, enterprise hosting, and WordPress and Joomla specific hosting.