7

Are there any eye-tracking case studies, or similar research done to verify what code format is easiest to read, maintain and work with?

I always format my code the following way:

function thing()
{
    if(something)
    {
      // do something
    }
    else
    {
      // do something else
    }
}

However, I never see this followed elsewhere. In most APIs or open-source projects, it's done like this.

function thing() {
    if(something) {
      // do something
    } else {
      // do something else
    }
}

Can you provide an answer that is not based upon your personal preference, but is supported by research or some kind of fact?

Has there been any visual eye-scanning studies done to confirm which format is best?

jub0bs
  • 109
Reactgular
  • 13,120
  • 4
  • 50
  • 81

2 Answers2

4

"Best" is relative.

Unfortunately, I can't remember the source. The studies I have seen or were referenced indicate that consistent visual style is the key for a project. Which particular house of style you worship at is less important than consistency. See Atwood's article for some additional references, especially to Code Complete: http://www.codinghorror.com/blog/2009/04/death-to-the-space-infidels.html

The premise is that if you're performing a code review, updating a new / foreign area, or bug hunting then the consistent presentation allows you, the developer, to more rapidly perform your task. A consistent style minimizes the time spent retraining / adapting while moving around in the code tree.

Here's an article from Joel Spolsky with some additional, and I believe researched, references: http://www.joelonsoftware.com/articles/Wrong.html

Either Atwood or Spolsky will lead you down the route to Martin Fowler and Refactoring, where there are more studies / references.

This appears to be an article related to your question and "readability statistics", but after skimming it, I can't fully vouch for the quality of research. It appears they borrowed the readability concept from regular writing and tried to apply it to code writing. http://www.comtor.org/wiki/images/4/4a/2009-Spring-Breese-A-499-PD.pdf

2

Whatever format a programmer is most used to reading is the format they will read fastest in. However, the minor differences between formatting matter little compared to how clear and concise the code and design is. In other words, I would not worry about newlines vs no-newlines and worry about terrible vs good code.

But to answer your question I prefer the second method, particularly when the // do something is one or two lines. If they are large blocks then you can refactor them into methods with clear names.

Garrett Hall
  • 2,192