Menu Search
Jump to the content X X
Smashing Conf New York

You know, we use ad-blockers as well. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. our upcoming SmashingConf New York, dedicated to smart front-end techniques and design patterns.

Why Coding Style Matters

When I was studying computer science in college, I had one extremely tough professor. His name was Dr. Maxey and he taught the more complicated courses like data structures and computer architecture. He was a wonderful teacher with a talent for articulating difficult concepts, but also an extremely tough grader. Not only would he look over your code to make sure that it worked, he would take off points for stylistic issues. [Links checked February/17/2017]

If you were missing appropriate comments, or even if you misspelled a word or two in your comments, he would deduct points. If your code was “messy” (by his standards), he would deduct points. The message was clear: the quality of your code is not just in its execution but also in its appearance. That was my first experience with coding style.

Further Reading on SmashingMag: Link

What’s A Style Anyway? Link

Coding style is how your code looks, plain and simple. And by “your,” I actually mean you, the person who is reading this article. Coding style is extremely personal and everyone has their own preferred style. You can discover your own personal style by looking back over code that you’ve written when you didn’t have a style guide to adhere to.

Everyone has their own style because of the way they learned to code. If you used an integrated development environment (IDE) like Visual Studio to learn coding, your style probably matches the one enforced by the editor. If you learned using a plain text editor, your style likely evolved from what you thought was more readable.

Style Guide
Not only publishing houses need a style guide. If you want to keep your code readable and easy to maintain even years after you’ve released a website, a coding style guide is helpful and necessary. (Image credit: Wikidave)5

You may even notice that your style changes from language to language. The decisions that you made in JavaScript might not carry over to your CSS. For instance, you might decide JavaScript strings should use double quotes while CSS strings should use single quotes. This isn’t uncommon as we tend to context switch when we switch back and forth between languages. Still, it’s an interesting exercise in self-observation.

Coding style is made up of numerous small decisions based on the language:

  • How and when to use comments,
  • Tabs or spaces for indentation (and how many spaces),
  • Appropriate use of white space,
  • Proper naming of variables and functions,
  • Code grouping an organization,
  • Patterns to be used,
  • Patterns to be avoided.

This is by no means an exhaustive list, as coding style can be extremely fine-grained, such as the Google JavaScript Style Guide176, or more general, such as the jQuery Core Style Guidelines167.

It’s Personal Link

The personal nature of coding style is a challenge in a team atmosphere. Oftentimes, seeking to avoid lengthy arguments, teams defer creating style guides under the guise of not wanting to “discourage innovation and expression.” Some see team-defined style guides as a way of forcing all developers to be the same. Some developers rebel when presented with style guides, believing that they can’t properly do their job if someone is telling them how to write their code.

I liken the situation to a group of musicians trying to form a band. Each one comes in believing that their way of doing things is best (their “method” or “process”). The band will struggle so long as everyone is trying to do their own thing. It’s impossible to create good music unless everyone in the band agrees on the tempo, the style and who should take lead during a song. Anyone who has ever heard a high school band perform knows this to be true. Unless everyone is on the same page, you aren’t going to accomplish much.

That’s why I strongly recommend style guides for software development teams. Getting everyone on the same page is difficult, and the style guide is a great place to start. By having everyone write code that looks the same, you can avoid a lot of problems down the road.

Communication Is Key Link

“Programs are meant to be read by humans and only incidentally for computers to execute.”

— H. Abelson and G. Sussman (in “Structure and Interpretation of Computer Programs”)

The most important thing when working on a team is communication. People need to be able to work together effectively and the only way to do that is by communicating. As developers, we communicate primarily through code. We communicate with other parts of the software through code and we communicate with other developers through code.

While the software your code communicates with doesn’t care how the code looks, the other developers on your team certainly do. The way code looks adds to our understanding of it. How many times have you opened up a piece of code that somebody else wrote, and, before doing anything else, re-indented it the way that you like? That’s your brain not being able to figure out the code because of how it looks. When everyone is writing code that looks different, everyone is constantly trying to visually parse the code before being able to understand it. When everyone is writing code that looks the same, your brain can relax a bit as the understanding comes faster.

BBC GEL8
Not only designers can use style guides to ensure consistent visual design and informed design decisions (like in BBC’s GEL9 example above). We could use them on the macrolevel as well: for the little fine details in our code.

When you start thinking of code as communication with other developers, you start to realize that you’re not simply writing code, you’re crafting code. Your code should clearly communicate its purpose to the casual observer. Keep in mind, your code is destined to be maintained by somebody other than you. You are not just communicating with other members of your team in the present, you’re also communicating with members of your team in the future.

I recently received an email from someone who is working on code that I wrote 10 years ago. Apparently, much to my shock and horror, my code is still being used in the product. He felt compelled to email me to say that he enjoyed working with my code. I smiled. My future teammate actually did appreciate the coding style I followed.

Leave Yourself Clues Link

“If you know your enemies and know yourself, you will not be imperiled in a hundred battles.”

— Sun Tzu (in “The Art of War”)

Knowing yourself is important in life as well as coding. However, you’ll never know yourself well enough to remember exactly what you were thinking when you wrote each line of code. Most developers have experienced looking at a very old piece of code that they wrote and not having any idea why they wrote it. It’s not that your memory is bad, it’s just that you make so many of these little decisions while writing code that it’s impossible to keep track of them all.

Writing code against a style guide outsources that information into the code itself. When you decide when and where to use comments, as well as which patterns should and shouldn’t be used, you are leaving a breadcrumb trail for your future self to find your way back to the meaning of the code. It’s incredibly refreshing to open up an old piece of code and have it look like a new piece of code. You’re able to acclimate quickly, sidestepping the tedious process of relearning what the code does before you can start investigating the real issue.

As Chris Epstein10 once said during a talk, “be kind to your future self.”

Make Errors Obvious Link

One of the biggest reasons to have a coherent style guide is to help make errors more obvious. Style guides do this by acclimating developers to certain patterns. Once you’re acclimated, unfamiliar patterns jump out of the code when you look at it. Unfamiliar patterns aren’t always errors, but they definitely require a closer look to make sure that nothing is amiss.

For example, consider the JavaScript switch statement. It’s a very common error to mistakenly allow one case to fall through into another, such as this:

switch(value) {
    case 1:
        doSomething();

    case 2:
        doSomethingElse();
        break;

    default:
        doDefaultThing();
}

The first case falls through into the second case so if value is 1, then both doSomething() and doSomethingElse() are executed. And here’s the question: is there an error here? It’s possible that the developer forgot to include a break in the first case, but it’s also equally possible that the developer intended for the first case to fall through to the second case. There’s no way to tell just from looking at the code.

Now suppose you have a JavaScript style guide that says something like this:

“All switch statement cases must end with break, throw, return, or a comment indicating a fall-through.”

With this style guide, there is definitely a stylistic error, and that means there could be a logic error. If the first case was supposed to fall through to the second case, then it should look like this:

switch(value) {
    case 1:
        doSomething();
        //falls through

    case 2:
        doSomethingElse();
        break;

    default:
        doDefaultThing();
}

If the first case wasn’t supposed to fall through, then it should end with a statement such as break. In either case, the original code is wrong according to the style guide and that means you need to double check the intended functionality. In doing so, you might very well find a bug.

When you have a style guide, code that otherwise seems innocuous immediately raises a flag because the style isn’t followed. This is one of the most overlooked aspects of style guides: by defining what correct code looks like, you are more easily able to identify incorrect code and therefore potential bugs before they happen.

Devil In The Details Link

In working with clients to develop their code style guides, I frequently get asked if the minutia is really that important. A common question is, “aren’t these just little details that don’t really matter?” The answer is yes and no. Yes, code style doesn’t really matter to the computer that’s running it; no, the little details matter a lot to the developers who have to maintain the code. Think of it this way: a single typo in a book doesn’t disrupt your understanding or enjoyment of the story. However, if there are a lot of typos, the reading experience quickly becomes annoying as you try to decipher the author’s meaning despite the words being used.

Coding style is a lot like that. You are defining the equivalent of spelling and grammar rules for everyone to follow. Your style guide can get quite long and detailed, depending on which aspects of the language you want to focus on. In my experience, once teams get started on coding style guides, they tend to go into more and more detail because it helps them organize and understand the code they already have.

Order In Your Code
In art, numbers are usually chaotic and serve a visual purpose. But you need order in your code. (Image credit: Alexflx54)11

I’ve never seen a coding style guide with too much detail, but I have seen them with too little detail. That’s why it’s important for the team to develop a style guide together. Getting everyone in the same room to discuss what’s really important to the team will result in a good baseline for the style guide. And keep in mind, the style guide should be a living document. It should continue to grow as the team gets more familiar with each other and the software on which they are working.

Tools To Help Link

Don’t be afraid of using tools to help enforce coding style. Web developers have an unprecedented number of tools at their fingertips today, and many of them can help ensure that a coding style guide is being followed. These range from command line tools that are run as part of the build, to plugins that work with text editors. Here are a few tools that can help keep your team on track:

  • Eclipse Code Formatter12
    The Eclipse IDE has built-in support for code formatting. You can decide how specific languages should be formatted and Eclipse can apply the formatting either automatically or on demand.
  • JSHint13
    A JavaScript code quality tool that also checks for stylistic issues.
  • CSS Lint14
    A CSS code quality tool by Nicole Sullivan and me that also checks for stylistic issues.
  • Checkstyle15
    A tool for checking style guidelines in Java code, which can also be used for other languages.

These are just a small sampling of the tools that are currently available to help you work with code style guides. You may find it useful for your team to share settings files for various tools so that everyone’s job is made easier. Of course, building the tools into your continuous integration system is also a good idea.

Conclusion Link

Coding style guides are an important part of writing code as a professional. Whether you’re writing JavaScript or CSS or any other language, deciding how your code should look is an important part of overall code quality. If you don’t already have a style guide for your team or project, it’s worth the time to start one. There are a bunch of style guides available online to get you started. Here are just a few:

It’s important that everybody on the team participates in creating the style guide so there are no misunderstandings. Everyone has to buy in for it to be effective, and that starts by letting everyone contribute to its creation.

(cp)

Footnotes Link

  1. 1 https://www.smashingmagazine.com/2008/08/7-principles-of-clean-and-optimized-css-code/
  2. 2 https://www.smashingmagazine.com/2008/11/12-principles-for-keeping-your-code-clean/
  3. 3 https://www.smashingmagazine.com/2011/01/cleaning-up-the-mess-how-to-keep-your-coding-workflow-organized/
  4. 4 https://www.smashingmagazine.com/2015/07/development-to-deployment-workflow/
  5. 5 http://www.flickr.com/photos/wikidave/7118464049/sizes/c/
  6. 6 https://github.com/google/styleguide
  7. 7 http://docs.jquery.com/JQuery_Core_Style_Guidelines
  8. 8 http://www.bbc.co.uk/gel
  9. 9 http://www.bbc.co.uk/gel
  10. 10 http://chriseppstein.github.com/
  11. 11 http://www.flickr.com/photos/73807667@N02/8021619893/sizes/c/
  12. 12 http://eclipseone.wordpress.com/2009/12/13/automatically-format-and-cleanup-code-every-time-you-save/
  13. 13 http://jshint.com
  14. 14 http://csslint.net
  15. 15 http://checkstyle.sourceforge.net/
  16. 16 http://docs.jquery.com/JQuery_Core_Style_Guidelines
  17. 17 https://github.com/google/styleguide
  18. 18 https://github.com/google/styleguide
  19. 19 https://github.com/rwldrn/idiomatic.js/
  20. 20 https://github.com/necolas/idiomatic-css
  21. 21 https://github.com/styleguide/

↑ Back to top Tweet itShare on Facebook

Nicholas C. Zakas is a principal architect at Box, as well as an author and speaker. He worked at Yahoo! for almost five years, where he was front-end tech lead for the Yahoo! homepage and a contributor to the YUI library. He is the author of Maintainable JavaScript (O’Reilly, 2012), Professional JavaScript for Web Developers (Wrox, 2012), High Performance JavaScript (O’Reilly, 2010), and Professional Ajax (Wrox, 2007). Nicholas is a strong advocate for development best practices including progressive enhancement, accessibility, performance, scalability, and maintainability. He blogs regularly at https://www.nczonline.net and can be found on Twitter via @slicknet.

  1. 1

    Zack Grossbart

    October 25, 2012 3:12 pm

    Thanks for the awesome article. I couldn’t agree more about code style. You mentioned Checkstyle and the Eclipse code formatter. I wrote an article a while ago including links to the Checkstyle checks and Eclipse code format my team uses. It also discusses a great code checking tool called Sonar.

    I hope this article about code formatting helps.

    1
  2. 2

    Great Article Nicholas! I think everyone should make sure to take the time when first getting into learning a new language, to first make sure that they are learning the right way to code in it. That way as your growing in the language, by the time your good you’ll understand what it is to write clean code in that language.

    This is very important when working in teams too. From my experience working with other developers who have no style in their personal approach or team understanding on what good code should look like, then the code is going to start looking like a warzone.

    0
  3. 3

    Case fall-through is one of the most evil little ideas in most languages. It’s one of the most error prone constructions ever and to be honest – you should probably just pretend like it doesn’t exists. ^_^

    0
    • 4

      There is at least one *good* use case for fall-through, and that’s when several cases are handled identically. Some languages will allow you to create a single multi-condition case (the Select Case structure in Visual Basic/VB.NET is a good example, no matter what you think of the language in general); C-style languages only allow a single test, so unless you want to violate DRY, stacking cases (with no code between them, and commenting the fall-through) is the right way to go:

      case foo: //falls through

      case bar:

      [code goes here]

      0
      • 5

        Instead of using fall through you can also conform with DRY by putting the shared code in a function, and call that function from each case separately. (Don’t forget the break statements! :-))

        I’m not saying you should, just that you could. Personally I think I would prefer fall through in most cases (haven’t used it for a while).

        0
    • 6

      Actually, C# doesn’t allow it: a fact for which I’m always most grateful…

      0
    • 7

      Jostein Berrefjord

      October 27, 2012 10:53 am

      I have been in touch with a huge number of very different languages, from Fortran and Cobol to APL, Prolog and Lisp, an then the huge crop of “algorithmic” languages with Algol, Pascal, Ada, CHILL, and of the various C derivatives.

      I have never seen a language whose syntax did NOT grow out from C that allowed silent case fall-through. Implicit fall-through is strictly limited to the C family of language syntaxes, and not even all of those: In C#, silent fall-through is a syntactical error.

      Silent fall-through is one of the most prominent reasons why C is described as a “You asked for it, You got it”-language. It certainly is not the only reason why C is in that category of languages, though.

      0
  4. 8

    True enough.

    I can’t count how many times I’ve revised my coding style, however I HAVE been happier with each subsequent revision. Overall, the goal is to simply make consumption of and comprehension of what you see easier.

    We have a term called “octopussing”, which is that natural state in how one area of your code needs to work with other, sectioned and compartmentalized areas of code. This is normal. However, when this gets out of hand, we call it “squidding”, because it’s got more arms than it needs, which usually calls for a code style re-evaluation.

    0
  5. 9

    Victor Sarabia

    October 25, 2012 11:54 am

    Thank you for the article Nicholas and especially for the reference links. As a self-taught programmer, this is an area where I have always felt at a disadvantage.

    Until very recently, I was unfamiliar with things like PHPDoc, which now I have started using in my WordPress projects.

    0
  6. 10

    Funny to see this article a week after attending Douglas Crockford’s “Programming style and your brain” talk at Web Directions South, as they have so much in common.

    Great article, and the principle of neatness can be applied to pretty much anything. From Photoshop documents to wire-framing, from programming to a clean desk policy ;)

    0
  7. 11

    A good rule about clean code:

    “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability”

    4
  8. 12

    Have you ever smiled about beaucracy running amok? That, of course, is a matter of perspective. To an observer it may be funny to watch an overly complicated process which mostly has become its own purpose and not whatever it was originally intended for. As its ‘victim’ you will not find it funny at all. The beaurocrats possibly had good reasons for each and every step they required, but the result is not pleasant. Not even for the beaurocrats themselves.

    Granted, anarchy will not lead to any useful results. In every team you will need a man to coordinate the effort and give the orders. There will also have to be some rules and regulations for the same purpose.

    Just like the beaurocrats, you may have valid reasons for your style rules. The problem is, that you also consequently must then try to cover every possibility, which leads to more and more rules. You may find yourself in the same trap as the beaurocrats.

    Your developers find themselves spending more time wrestling with all kinds of styles and conventions than actually doing anything productive. For example, a style checker with too many rules and treating everything as an error can quite efficiently prevent a developer from trying out some new code to verify some assumptions. This code is not intended to be checked in or used productively, but the style checker will not let the developer find out what he wants to know unless he jumps through each and every hoop it could find. What a waste of time.

    And do you really want good soldiers that obey each and every command, rule or regulation without thinking? After a certain point they will not be able to see the intentions behind the rules and have little choice than to obey them blindly. I prefer to let developers run into problems and even make mistakes. Preferrably only twice: For the first and the last time, This way I hope to get experienced developers who I can rely on to make valid decisions, assume responsibility for what they are doing and, not least, gain a little pride in their accomplishments.

    I admit that this is a harder way, a little less predictable or ratable. And I can clearly see why managers may not like that at all.

    1
    • 13

      I completely agree. I’ve had to work with people who would reject complete change sets because of a single misplaced space, a missing comment, or a line that is too long all because it did not follow the rules, all while missing a the fact that I had reversed the logic in a method. Some people really love rules. I suppose it is an ego thing that make them feel more important.

      3
  9. 14

    Hi Nicholas – I have to say, that bit about missing out the break in the switch statement really ‘clicked’ for me.

    I never actually thought about it that way, and while I’ve never really bothered to comment my code before, I’ll definitely be doing it from now on. Just makes so much sense!

    Thank you!

    0
    • 15

      Ironically, that’s a very good point against style guides and automated checking tools. A possible problem has come to your attention, a simple solution has been shown and now you want to keep an eye on that and also look out for similar cases. It’s yet another little step of experience on the never ending road to become an experienced developer.

      Style checking tools would force you to comply to all kinds of rules. The rules may have a purpose, but this way the developers learn little to nothing. If I have a choice, I always prefer developers who know what they are doing over well trained code monkeys.

      0
  10. 16

    Totally agree, I think it’s easy to follow a coding style, it’s just matter of practice

    0
  11. 17

    Sarfaraz Ansari

    October 25, 2012 8:46 pm

    Thanks for such a nice article i am totally agree with you.

    “If someone is at your position, how fast he understands your work. This all says about organized work.”

    0
  12. 18

    Michael Talburt

    October 25, 2012 9:17 pm

    Great article Nicholas! I guess, it’s the first rule of every web designer to have his own style of coding.. In that way they can recognize their work from others. Most especially, in this field were anyone can take inspiration from anyone, it is a great way to make a genuine touch in its own work.

    0
    • 19

      You probably work for yourself / alone?

      0
      • 20

        You should grant him the courtesy of assuming that he has made a few experiences of his own and may have his own good reasons to do things the way he does. I see it as a great waste when the individual developers’ experience is discarded by enforcing the ‘one and only’ correct style.

        1
    • 21

      I’m all for setting yourself apart with a personal touch, but I’m not sure your code is the place to do it. I always write with clear, concise style and logic. Nicholas means that a coding style promotes consistency, especially within teams. I do work alone, but I don’t code as if I’m alone. I work with the assumption that someone else is going to look at it, even if it’s just me in the future. I wouldn’t want to have to stand over anyone’s shoulder to point out the quirks of trying to leave my signature in the code itself.

      If I want to mark something as mine, I’ll do it with the implementation. And maybe a block comment. :P Of course, I have to admit I’m rather flattered when someone borrows a snippet from me here or there. It just means my code is flexible enough to find life beyond a single script. I’m especially happy if it doesn’t break their code.

      0
  13. 22

    Why don’t you write:

    switch(value) {
    case 1:
    doSomethingComplex();
    break;
    case 2:
    doSomethingElse();
    break;
    default:
    doDefaultThing();
    }

    doSomethingComplex() {
    doSomething();
    doSomethingElse();
    }

    I think that the naming of methods is important here and complexity should be reduced at any cost. You should not use fallthrough in that simple case of deciding between 3 ways to go. It should be rarely used in my opinion (The only use case I can imagine now is a parser that matches a (big) set of terminal symbols = classification of those symbols).

    I also think that the comment above ( //falls through ) isn’t really making things better here because you have to understand the complexity/ the whole picture of the problem anyway to make good decisions then adding new code to the statement above. The comment will probably become outdated at some point in time – causing other bugs and misunderstandings. If you are tempted to add explanatory comments to your code it might be a hint that your code has become too complex. You might be dooing too much in one method, for example.

    (“Clean Code” is a really good book! Especially for Java developers.)

    0
  14. 23

    On a side note, if you use PHP you should consider using PHP_CodeSniffer (phpcs) as there are plugins for all the major popular frameworks standards (like Zend, Symphony, Cakephp, etc. ) and it plays nice with continuous integration servers like Jenkins.

    http://pear.php.net/package/php_codesniffer

    0
  15. 24

    Matthew Graybosch

    October 26, 2012 5:11 am

    The fact that case fall-through is permitted in JavaScript doesn’t imply that it should be used. In your place, I would have written the example so that case 1 called doSomething() and then doSomethingElse(), and then added a break statement to avoid the sort of ambiguity which makes comments necessary.

    0
    • 25

      It’s however hard to understand why the delicate case is the “default” one… actually there should be a key-word fallthrough; and developers not forced to note the break; vice-versa the very most of their times being.

      0
  16. 26

    Darryl Wagoner

    October 26, 2012 5:20 am

    I have always considered coding standards important, but it is just the start. Your code needs to be SOLID and clean. I very much recommend the book Clean Coding … by
    Robert “Uncle Bob” Martin. I read the book a few years ago and it changed my life as a programmer.

    Happy Coding!

    0
  17. 27

    Thank you thank you thank you. (I’m sure my future self will thank you, too.)

    0
  18. 28

    Coding style is about presentation. It must be clear and distraction free. Which is why its tough to take your article seriously when there are a million adds and other bits of distracting nonsense on the right side of your web site.

    0
  19. 29

    One thing I’ve mulled over a bit is why our tools haven’t advanced even more than they have. I could go on about that in several ways, but I’ll stick with code style here. Perhaps we should separate the code “model” from the code “view.” After all, the compiler doesn’t really care, and thus there is can be a canonical representation of the code. What if THAT is what actually gets stored instead of our formatted text? Then the editor we’re using would apply something akin to a style sheet to that canonical form. Each developer would have a view into the code that is most readable for him or her.

    Obviously this doesn’t cover everything such as patterns to use / avoid and when and where to use comments. And it would require some “smarts” to match up errors with locations in the code using something other than line numbers. Although I’m not sure that would be such a bad thing – line numbers always struck me as a bit weak anyway as a debugging tool.

    Not sure if these are good ideas or not, just something I’ve batted around in my head a little. I do think there is a lot that can be done in the realm of tools – in many ways I feel like I’m still coding like it’s 1989.

    0
    • 30

      Eddie, tools have become very advanced, but most new coders have not seen a real CASE tool, and would not recognize one to save their lives. When I was coding in the early 1990’s, it was not uncommon to spend $50,000 per seat licensing or more on software tools like BattleMap (which has been acquired by McCabe software, renamed IQ Enterprise Edition, and repriced lower, but still very expensive).

      Both HP and DEC had similar suites of tools in that period of time, but mostly could not touch BattleMap. DEC’s VMS had an amazing documenting editor called LSE, for example, and automatic versioning in the file system so you never lost edit history; still not something that can be done on UNIX systems, due to doing the globbing in user space rather than the kernel, so asking for a file “foo.c” would get you foo.c;23, and when you saved it, you got foo.c;24, and could request specific versions by adding the appropriate suffix.

      In general, relatively speaking, the free stuff is crap, and if you get into some place that uses the free stuff, right out of college (e.g. Google seems to be in love with Gerritt and Perforce – though the latter is not free for non-open source), you’re going to be trained up on inferior tools and not know better due to lack of exposure. If you were a carpenter or mechanic, it’s be like never having worked in a fully equipped shop and still using a brace and bit to drill your holes in things.

      if you think I have left out things like Rational Rose and Eclipse or Visual Studio Or XCode, they’re only marginally better than the free tools, since they are mainly based on them, and not very complete environments on their own. The debugging in XCode is particularly bad even compared to VisualStudio, and neither of then can do what BattleMap did, in 1992, which was full branch path analysis, requirements to use case to test cases — with 100% code coverage for unit tests. It was a joy to work in such an environment, though at nearly twice the starting salary of a BS in CS just starting out, the price was steep (and it’s still steep, but less so).

      0
  20. 31

    Nice article. Wanted to add a methaphor that came to my mind: when writing a code, that other people or you yourself may read in future – treat it like a story. Well written story is easy to read and easy to get the sense out of it. If writer is hard to read, no matter how well his ideas are, you are not likely to follow them.

    0
  21. 32

    Interesting article. This is one thing that was not covered when I was learning to program. However, I do use MS VS (Microsoft Visual Studio) and C#, and the style for the braces ({ } <<< these funny looking things) are set to the C language style, and I like it that way. It keeps it nice and tidy for me to follow through the code.

    Your touch on commenting is also very good, and its something I do. Others read my code, and for others to be able to understand what it does without having to figure it out is important. Others do read ones code, and most projects are upgrades of one version to another, and the program is not a "new" project. So yep, I'm all for this kinda stuff.

    0
  22. 33

    Another reason why good style matters: people learn from it. I learned the basics of html several years ago, but I’ve learned the most just by reading other people’s code. It’s the same with things like CSS and javascript. I’ve learned most of what I know by seeing something interesting and reading that snippet of code. By writing with better style, you help others write with good style.

    0
  23. 34

    A few comments (some a bit critical, sorry!) — <3 your books! Imagine any comments that might offend in the voice of a drunken gremlin.

    #1. Style guides are amazingly important, but unless it is absolutely required, never have the team come up with them. This is an endless circle jerk of debate. Generally you can find a definitive style guide for your language, use it. If you can't, or there are one or two competing, flip a coin! The debate and "fighting out" a style will lead to endless arguments, bitterness and resentment because someone is always going to be coding in a style they HATE… some people LOVE GNU code style, I call these people "the crazies". Making everyone sacrifice yet be profoundly involved and invested is like a self-inflicted team divorce… bitterness, anger and side taking!

    #2. Comments can be important, but meaningful naming is far more important and less likely to rot. There is a reason grizzled old coders love and hate comments… the hate comes from experience, nothing is more brutal or misleading than comment rot. The trick is keeping the comments very abstract and above the code. Explain why not what.

    #3. Your "//Falls though" is IMHO the WORST thing you can do in a comment, you are explaining syntax, and that is nonsense. It has exactly as much value as x+=1; // add one to the variable x (you write comments to explain WHY you are doing something, the source code defines WHAT you are doing in a structured and exacting manner… if it is hard to read, consider a different structure).

    2
  24. 35

    We agree that code quality can be measured by checking the code against a set of style rules, and while its not a functionality check, it certainly helps to make communication barriers between programmers within a team less of a problem.

    That’s why we developed http://lintme.com for in house use, and have recently been trying to make it available to everyone else.

    0
  25. 36

    Great article. I have to admit I have been guilty of writing awful code in the past.

    Now I try to write code as clean as possible because I don’t know who will be working with my code and the first impression always count even if it is just code.

    0
  26. 37

    A couple of thoughts, in addition to those raised in the article and in the comments:

    — Coding style “matters” also in the sense that being neat and clean about coding style carries over to the implementation details itself. That is, a person who is willing and able to pay attention to the fine details of code organization is also more likely to be willing and able to pay attention to the fine details that distinguish well-designed and carefully-implemented code from poorly-written code.

    As is the case for any professional endeavor, the better a person is at paying attention to the details, the more competently they will perform the duties of that profession.

    — In the team environment, it’s especially useful to be able to adjust to different coding styles. Not only is it necessary as one moves from one project to another, it’s also often the case that a given project may have more than one coding style. This can occur either because the style guide has evolved over the years, or because there was or is no style guide. IMHO it is more important to keep the style in a given module consistent than for any particular style to be followed.

    It’s definitely a mistake to go reformatting someone else’s code just because it doesn’t match what you want, but more than that, it’s also important to be able to maintain that code in the original style, rather than inserting your own style as you change things.

    A team works best when each member of the team is respectful of the bigger picture, rather than always trying to impose their own personal sense of right and wrong.

    0
  27. 38

    Another nice rule would be: “don’t use labels”. Or even more strict: “don’t use global variables”. Good code can be made without those.

    0
  28. 39

    Timothy C. Quinn

    October 27, 2012 6:44 pm

    Glad to see you are still cranking out the good ideas and code Nick. Thanks again for your contributions to the businesses and communities. I enjoy reading through your code and tweaking it when I have to.

    I still really like your slick window focus trap you wrote for M1 back in the day.

    Cheers,
    – Tim

    0
  29. 40

    For C#, I use StyleCop (http://stylecop.codeplex.com) with default settings on everything. After a few months, the style just flows out without minimal additional effort. The only painful thing it to fix, refactor and re-organize the code that other “super programmers” who deem style formatting a “waste of their time” and checked source code into the same project.

    0
  30. 41

    Martien de Jong

    October 28, 2012 1:22 am

    Some coding styles are better then others, but even the worst coding style can produce completely valid programs. A good programmer can work with any coding style. Thefore I think it is always good to discuss coding style but don’t get dogmatic in it. The program is usually more important than the code that makes it work.

    0
  31. 42

    Bert Laverman

    October 28, 2012 1:58 am

    I especially like the “Programs are meant to be read by humans and only incidentally for computers to execute.” quote. Not only style matters; the language has a big influence as well. I have always held that XML is great… for toolbuilders. It is thoroughly unfit for human consumption. Wrote a blog post about it: http://eleganceinsoftware.wordpress.com.

    0
  32. 43

    Philip Schwarz

    October 28, 2012 4:08 am

    I like Kent Beck’s idea of programming/development style in his book ‘Implementation Patterns’:

    “These three elements—values, principles, and patterns—form a balanced expression of a style of development. The patterns describe what to do. The values provide motivation. The principles help translate motive into action.”

    “One of the advantages of laying out a programming style as values, principles, and practices is that it is easier to have productive conflict about programming this way. If you want to do something one way and I another, we can identify the level of our disagreement and avoid wasting time. If we disagree about principles, arguing about where curly braces belong won’t solve the underlying discord.”

    Three key values:

    “When I am working well, I hold dear the importance of communicating with other people, removing excess complexity from my code, and keeping my options open. These values—communication, simplicity, and flexibility—color every decision I make while programming”

    Philip

    0
  33. 44

    Why coding style matters, when…

    …the code *will* be part of a project where you do not maintain total source control:

    1) be absolutely clear of intent
    2) in the CASE (pun) of SWITCH, comment fall-through cases, what CONTINUE logic anticipates, and what nesting level BREAK jumps out to
    3) encapsulate every logic branch succinctly, using braces {} to the max and further encapsulate logic in reusable standard functions, modules, subroutines, method calls, etc.
    4) use parentheticals () very sparingly, only really to address ambiguities resulting from the syntax of the code language, such as precedence of operations
    5) reuse a standard library of code first, invent and contribute to a standard library of code second, avoid inventing stand-alone or one-off solutions that are not reusable except when it makes no sense in any other context (like in protocol logic)
    6) do not ever use short-circuit logic, especially for nested conditionals
    7) avoid embedded data or interspersed data and logic (via heredoc, context switches like breaking out of PHP into output mode and back again, or otherwise) — declare the atomic bits of data ahead of time, then have the logic use and/or assemble the atoms into appropriate output
    8) succinctly comment on the purpose and logic of the code block, and — failing that — use the comment to reference a detailed comment at the end of the file *within the same file* (like a footnote) so that the explanation cannot be easily separated from the code it explains
    9) use tabs for indentation so people can set the indentation display size themselves to what is most readable for cursory inspection and comprehension of the code
    10) use UTF-8
    11) use UNIX newline \n line endings for everything, it is the most portable and leaves the least artifacts in text processing and display tools, even console-based ones
    12) separate code sections that deal with different conceptual tasks using blank lines to aid comprehension
    13) this floor does not exist
    14) explicitly type-cast if you must cast at all — don’t rely on built in type-casting to be obvious to the next person
    15) you’ve reached team coding nirvana

    …the code *may* at some point be useful enough to be used in a project where you do not maintain total source control:

    1) do the same as above, with an eye on a reusable code library, encapsulated functionality, … , profit! :)

    …the code *is only* to be used in a project where you maintain total source control:

    1) doing the same as above would benefit you in the form of self-training — making the above second nature

    2) if an aspect of your personal style provides a benefit that serves to offset a basic failing in the syntax or feature set of the code language then use it, but document it fully for your own comprehension later

    3) at the very least, establish a standard for your own coding style to which you rigorously adhere, so that you can function effectively and be productive in a team environment and/or are able to create useful code that others will want to use — for fun and profit!

    btw, this article got picked up by /.

    -1
  34. 45

    This article makes some excellent suggestions and prompts the reader to consider their own coding style. But how well does it answer the title question “why coding style matters?”

    0
  35. 46

    I fully agree that code styles are important, a sign of great craftmanship and also a sign of caring about the people after you, who will be maintaining the code. As for style, I think predictability and consistency are key. It doesn’t matter much how you place your curly braces, just be consistent in it.

    I’d definitely recommend in automating as much as you can, because anything that requires discipline or is considered “optional” will be the first thing to be under attack when a project is under pressure.

    Also, I’d like to emphasize that it is important which software development problems you give priority. As an example, if your code is cleanly styled yet poorly architected, the architecture issue is a bigger problem. Solve that one first. Do not underestimate architecture. In fact, code in a solid architecture needs very little documentation, because the context (method name, layer in which it is contained) already tells what the code does.

    And a final tip on code commenting. Don’t comment like this:

    // create a new connection object
    var objConnection = new Connection()

    I see this all the time. That comment is not helpful. You should comment what you’re trying to accomplish, why and how.

    0
  36. 47

    i guess coding style depends on company or i say customer who will get the final product
    so its totaly depends on ur location head and client

    0
  37. 48

    Justin Fortuna

    October 30, 2012 7:41 am

    I love how you emphasized the importance of style and relayed to TEAM COMMUNICATION! Great article! Having a clean style and a solid architecture can save hundreds of hours on large group projects!

    0
  38. 49

    good job im 6y/o

    0
  39. 50

    Bryan Hadaway

    October 31, 2012 3:37 am

    I actually have a very unorthodox style of coding that many would not agree with.

    To put it simply in a sense, I have no style. Or to phrase that better I remove typical style and/or not add it in the first place.

    I do not use line breaks, spaces, indentation, white space or anything else that is unnecessary to the code functioning. It’s clean and valid code (I certainly care), but semi-minified for speed.

    Another thing I refuse, that most coders will shake a stick at me for, is to add programmer comments. I think it’s messy, ugly and wastes a lot of space and load time (it is important to note that I one-man-show nearly all my projects).

    For me, I think it’s better to have clean code and files and instead of making the filesize twice the size with inline comments, to reference documentation on your website.

    Thanks, Bryan

    -3
    • 51

      the code is the thing – nothing else matters – anything else in fact is a distraction – comments are evil – a reflection of the fear of program complexity which is a hobgoblin of lesser minds – program logic is already precisely expressed in code – it is exactly what it is – no more no less – if you need comments to understand the code you have no business working on it

      -2
  40. 52

    Namanyay Goel

    November 1, 2012 5:20 am

    Great post, love the way you compare things to examples! Makes the whole thing really easy to understand :)

    0
  41. 53

    Style is definately important, but like all things some aspects are more important than others. These should be prioritized and the effort put there.

    Top of my list would be:

    * Indent – spaces or tabs and how many (to get editor set up right).
    * Structure breakers (such as your example of switch fall through but also things like embeded returns) should be well commented.
    * Assumptions and constraints should be documented.
    * APIs should be documented.
    * A general requrement that indentation reflects nesting and similar things should line up when practicable.

    But down the bottom of the list would be things like should there be spaces before/after round brackets or where to put the opening ‘{‘. I know what I like, but it only makes a small difference to readability but will cause endless arguments and it takes a lot of effort to retrain ones fingers.

    0
  42. 54

    Very good Article. Thanks for sharing this.

    0
  43. 55

    I’m not really into programming even I am a graduate of IT. but then your article is nice and well written for me. different styles on coding means also on how you understand it and how your logic works. Thanks for the article!

    0
  44. 56
  45. 57

    what has happened to the state of web design? So many articles about organizing style sheets and proper code form. Where to indent and not, alphabetizing selectors. The banishment of tables as structure and the amazing human ingenuity of the clear.gif. What happened to us? It was free form, banging out a tune on an off-key piano. No time to tune you correct each off-note as it comes. You throw paint a canvas not draw grids with rulers. Designing for the web was four guys in a dark room playing jazz with cigarette smoke and old stale sandwiches left on moms plates. Now its glass windowed cubes with no finger smudges. No finger smudges! Its not possible, glass has smudges on it! Its our finger prints! The clean, shinny surfaces used to cling to those finger prints and now they are manufactured, on purpose to repel them.

    0
  46. 58

    I think this is an important topic, I have worked on a variety of projects on a variety of platforms and structured code full stop, not just CSS is great when working on something that I haven’t started from scratch.

    Ever since I started developing online Ive tabbed all of my code so that the structure as detailed in the article is in place. It makes it easier to follow and amend, especially if someone else picks up the work after me.

    Also sufficient use of comments is great for future developers. Remember that how you code something may not be glaringly obvious to someone else.

    The difference in file size when creating a nice structure in your code is not going to be vast, try focusing on reducing media file sizes and js files to scrape back the odd kb lost in structured code.

    0
  47. 59

    As for jQuery Core Style Guidelines, I’ve been following it for about a year. Everything suits me except I couldn’t find any decent validator on the Internet. I’m used to check how my php sources adhere ZF coding style by PHP_CodeSniffer, but I didn’t find anything like that for JavaScript and eventually came up with JS_CodeSniffer https://github.com/dsheiko/jscodesniffer

    0
  48. 60

    nice article

    0
  49. 61

    Gretchen in KS

    June 24, 2014 1:06 pm

    I’ve just been introduced to coding, (actually, my company lost our IT person, and I inherited some of his chores.) We were lucky enough that he’s still on speaking terms with us, and left us some codes he had made up over the years, but it still feels a bit like falling into the deep end of the pool. Before this, I’d only had one very brief class on Basic, and no, he wasn’t, and thus I’m not, using Basic now. (Pearl, I think it is. Not heavy stuff, just little scripts, but when we need one, we need one NOW.)

    Great article! It helps to clarify some of the things I have just begun to parse out in the codes I’ve begun to need to edit, here and there. I do think, however, that I’m going to need to hit up the bosses for time and funds for a course in beginner programming, or very generalized IT topics. This sparks ideas, for me, on where to start.

    0
  50. 62

    Great article !

    Totally agreeing with your point of view. But sometimes, when trying to maintain a proper code you can face some situations leading to “not really human readable code”.

    In example if you are limiting the column number to 80 characters. Your methods need to be well named and can sometimes be really long. Adding two arguments to this declaration line and you have to put your arguments in the line below. This can make first code read hard.

    In conclusion, a well written code is a smart balance between coding standards and “direct readability”.

    0

↑ Back to top