Studies on optimal code width? [closed]
Asked Answered
M

11

184

If you enable the "View Right Margin" in your IDE of choice, it is likely that it will default to 80 characters. I tend to change it to 120 for no reason other than it was the standard at a company I was with a few years back, and no other company has told me to do it differently.

My question is, are there any studies that actually show 80 characters to be the optimal maximum width for code readability, or is this value just a "that's the way it's always been" and no one really knows why it is that way? And, should the width of a line of code be part of your coding standard?

Malefaction answered 23/2, 2009 at 15:40 Comment(10)
While I don't know of any studies, you'll find plenty of opinions as answers to this question: * Is there a valid reason for enforcing a maximum width of 80 characters in a code file, this day and age?Stedfast
no studies that I know of but you might find it interesting to look at different projects coding standards. For example Google's are 80 characters. (code.google.com/p/google-styleguide) where as WebKit (ala Apple's?) have no limit AFAIK (webkit.org/coding/coding-style.html). Mozilla's appears to be 80 (developer.mozilla.org/En/Mozilla_Coding_Style_Guide#Line_length)Cienfuegos
Perhaps related (for prose): en.wikipedia.org/wiki/Line_lengthRevisionism
a good formatting style enforced by tooling can help a lot hereDiogenes
Required a 2022 answerJuni
"no one really knows why it is that way?" -- we very much know why it is that way: ibm.com/ibm/history/ibm100/us/en/icons/punchcardWebb
I suppose it's a good thing this was closed, not for the bogus reason given, but because the "answers" don't answer the question and are just rationalizations, often profoundly stupid ones like "I'd say the same general principles for optimal line length in books are applicable to reading code. That is, narrower columns are read more quickly, whereas wider columns are read more slowly." -- reading code as quickly as possible is not a goal.Webb
There's plenty of good reasons to extend line length from 80 to 120, and plenty of problems leaving it at 80. There's nothing arbitrary about those lengths. I'm considering a line length limit of 150. The best decisions are not always popular but the reasons for that are genuinely obscure.Zenia
@JimBalter "reading code as quickly as possible is not a goal." - there are many quotes advocating otherwise -- that we read code more often than we write it, so it is important that the code is easy to read. Three such quotes: "It is harder to read code than to write it." - Joel Spolsky "So if you want to go fast, if you want to get done quickly, if you want your code to be easy to write, make it easy to read." - Robert C. Martin. "Programs must be written for people to read, and only incidentally for machines to execute." - Harold AbelsonHoofbound
" there are many quotes advocating otherwise" -- no there aren't. "that we read code more often than we write it, so it is important that the code is easy to read." -- a different issue entirely from speed reading code.Webb
P
143

Actually, the 80-column thing long precedes DOS. It comes from card punches, which were 80-column devices.

And to kind of answer the OP's question, one "study" has been going on for about 600 years now - the printed book. These have evolved over the centuries, with readbility foremost in mind, to the position we are at now where the average line length for text is around 60 characters. So for readability, go for narrower margins.

Play answered 23/2, 2009 at 15:47 Comment(12)
I really don't believe you can compare reading natural language with reading a programming language in terms of usability.Hindenburg
@Hindenburg - actually, you probably can. The reason for the 65 character width isn't because larger lines can't be read, but that it's too tight an arc when the eye moves to the next line. You can get around this by increasing line height, but that makes it harder to use block spacing to convey meaning, so it's probably something to avoid in an IDE.Coincidence
@Jim - My natural language doesn't contain words with 30 characters in it (not that I use anyway) and it parses completely differently than a programming language. You can often group a line of code as separate from the rest, be it a long conditional or a combination of long methods and classes. Combine this with indentation and the comparison between the two languages becomes absurd. I have no doubt anyone scientifically studying readability and line length would object to your washing over the differences.Hindenburg
@Hindenburg - I don't really see how your objections engage with any of the claims I made, but I can see that indentation breaks the model I'm proposing. Don't call me 'Jim', though.Coincidence
I second that you should look how books do it more often. For example, it irritates me how bad software often is at putting margins or similar space where it is needed. E.g. in Eclipse there is no space between line numbers and program text.Pyxie
A book is typically placed much closer to the eyes than a monitor, which means that fewer characters per line is allowed if the reader is to be able to read the book without having to crane the neck. A screen is typically not placed at the distance of a book, which means more characters per line can be used while keeping within the limits of the maximum eye angle. Also, code isn't read as much as it is perused, making this width less important. I (YMMV) can easily follow lines with 120 characters of code on my laptop screen, but this is too wide for 2 emacs buffers on my 15" laptop, alas.Chlorite
Let's just gather our gall and face the elephant in this room: @Obscaenvs just made more sense then everyone else here combined. Nailed the heart of the issue right on the head.Delectation
Thank you, @ChaseMoskal! ...now, where's that "Follow" button? :)Chlorite
This answer should have been downvoted not upvoted, it does not answer the question. It's just popular because so many programmers are opinionated about it.Talus
In these discussions people always pretend all the lines will have the limit.Perithecium
@Talus I downvoted it both because, as you note, it has nothing to do with the question but is just one person's baseless opinion, and also because the logic is absurd and doesn't even account for font size. The only good thing about it is that it correctly notes where 80 columns came from. (BTW, punch cards were 187 mm wide, which was not in any way related to the width of a book.)Webb
Somebody seems to have deleted Obscaenvs comment, @ChaseMoskal, apparently the most interesting and beneficial comment of all. Why doth censorship always have to seem as such?Zenia
P
166

Have mercy on the programmers who have to maintain your software later and stick to a limit of 80 characters.

Reasons to prefer 80:

  • Readable with a larger font on laptops

  • Leaves space for putting two versions side by side for comparison

  • Leaves space for navigation views in the IDE

  • Prints without arbitrarily breaking lines (also applies to email, web pages, ...)

  • Limits the complexity in one line

  • Limits indentation which in turn limits complexity of methods / functions

Yes, it should be part of the coding standard.

Pyxie answered 23/2, 2009 at 16:38 Comment(15)
These are great reasons to keep line width to 80 characters or less. I'm really surprised (disappointed) that your answer, which is clearly thought out and correct, didn't get more points. To this list, I would add: (1) horizontal scrolling is no fun. (2) You can greatly increase the density of the code you're working on by viewing that code in multiple colums. A great deal of real estate goes to waste when you have a few lines that extend far to the right when most of the other lines don't.Kelantan
ok but what happens when there is a block of code with few indentations ? that have happened to me and 80 characters are not fun at all.Incalescent
Limits the complexity in one line I'm not sure why spreading complexity across multiple lines is better. It just pushes more onto your mental stack.Rochellerochemont
This is a very old topic. but do you still agree now that loads of developers use 27 inch monitors :-). I mean if sight is an issue a bigger screen can help. 8 years ago we were still working on 17 or 20 inch monitors and some on 4:3 resolutions even.Codicodices
@MathijsSegers regardless of monitor size or resolution, it's still more comfortable to keep text within the middle 30 degrees of your field of vision. When working with multiple windows open in side-by-side monitors, I tend to turn my head to look from one to the other. A person shouldn't have to turn their head or rotate their eyes all the way in order to read from one end of a line to the other. So much rapid eye or head rotation would probably cause vertigo if done all day.Gerianne
Making the code narrower means that it ends up longer. So less can be seen at once. So it actually becomes harder to read IMHO.Litha
I'm a proponent of the 80 character limit, except for data tables (e.g. constant arrays of structs) where making rows span across multiple lines makes it harder to read. This is one exception where I don't mind horizontal scrolling for the sake or clarity and easier maintenance.Revisionism
I personally prefer 100 due to the fact I prefer 4 spaces indentation.Epinasty
@Rochellerochemont how does using line breaks push more onto a reader's mental stack?Ornithosis
🤔 Reading this answer 14 years later (as someone who indeed maintains earlier written code), it is amusing to see an 80-character recommendation given I have Visual Studio open right now on my 4k monitor with 4 side-by-side screens of code, each no less than 110 columns each. The codebases which hard wrapped lines prematurely to 80 are much harder to follow their zig-zag pattern of fragmented statements than the ones that target 80 but flexibly allow up to 120 columns.Melody
@DonnieCameron It shouldn't have received any upvotes since it doesn't answer the question. Neither do any of the other "answers", which are just opinions that have nothing to do with the question asked--about studies.Webb
@DwayneRobinson Indeed. Remarkable are the mental contortions that people will employ to rationalize an arbitrary number that comes from ancient technology: ibm.com/ibm/history/ibm100/us/en/icons/punchcardWebb
Yeah I don't have a horizontal scroll bar and with my meagre 1920x1080 display I end up cursing all day when I view code longer than 80 chars because of all the horizontal scrolling I have to do ;-)Zenia
About side-by-side argument: my 27" monitor shows with my (default) settings 302 characters in a line. So I can put 120 char-per-line code side by side and still have space left. @Zenia a 1920 pixel wide monitor should display 220 characters easily. With bigger font a comfortable 120 or so.Explicable
I was speaking ironically @DavidBalažic! Notice the wink? I literally have no horizontal scroll bar but it's no problem with my standard line length of 120 chars that I use and, yes, I too often use two windows side-by-side on the screen. I have pretty much decided, that next time I get to start from scratch I will use a 150 char line length. I'm fed up with having to crop my lines or jig my code to fit into 120 chars for no good reason when I have long strings or my best-practice long meaningful identifiers just add up to 3 characters too long. It's bad for readability!Zenia
P
143

Actually, the 80-column thing long precedes DOS. It comes from card punches, which were 80-column devices.

And to kind of answer the OP's question, one "study" has been going on for about 600 years now - the printed book. These have evolved over the centuries, with readbility foremost in mind, to the position we are at now where the average line length for text is around 60 characters. So for readability, go for narrower margins.

Play answered 23/2, 2009 at 15:47 Comment(12)
I really don't believe you can compare reading natural language with reading a programming language in terms of usability.Hindenburg
@Hindenburg - actually, you probably can. The reason for the 65 character width isn't because larger lines can't be read, but that it's too tight an arc when the eye moves to the next line. You can get around this by increasing line height, but that makes it harder to use block spacing to convey meaning, so it's probably something to avoid in an IDE.Coincidence
@Jim - My natural language doesn't contain words with 30 characters in it (not that I use anyway) and it parses completely differently than a programming language. You can often group a line of code as separate from the rest, be it a long conditional or a combination of long methods and classes. Combine this with indentation and the comparison between the two languages becomes absurd. I have no doubt anyone scientifically studying readability and line length would object to your washing over the differences.Hindenburg
@Hindenburg - I don't really see how your objections engage with any of the claims I made, but I can see that indentation breaks the model I'm proposing. Don't call me 'Jim', though.Coincidence
I second that you should look how books do it more often. For example, it irritates me how bad software often is at putting margins or similar space where it is needed. E.g. in Eclipse there is no space between line numbers and program text.Pyxie
A book is typically placed much closer to the eyes than a monitor, which means that fewer characters per line is allowed if the reader is to be able to read the book without having to crane the neck. A screen is typically not placed at the distance of a book, which means more characters per line can be used while keeping within the limits of the maximum eye angle. Also, code isn't read as much as it is perused, making this width less important. I (YMMV) can easily follow lines with 120 characters of code on my laptop screen, but this is too wide for 2 emacs buffers on my 15" laptop, alas.Chlorite
Let's just gather our gall and face the elephant in this room: @Obscaenvs just made more sense then everyone else here combined. Nailed the heart of the issue right on the head.Delectation
Thank you, @ChaseMoskal! ...now, where's that "Follow" button? :)Chlorite
This answer should have been downvoted not upvoted, it does not answer the question. It's just popular because so many programmers are opinionated about it.Talus
In these discussions people always pretend all the lines will have the limit.Perithecium
@Talus I downvoted it both because, as you note, it has nothing to do with the question but is just one person's baseless opinion, and also because the logic is absurd and doesn't even account for font size. The only good thing about it is that it correctly notes where 80 columns came from. (BTW, punch cards were 187 mm wide, which was not in any way related to the width of a book.)Webb
Somebody seems to have deleted Obscaenvs comment, @ChaseMoskal, apparently the most interesting and beneficial comment of all. Why doth censorship always have to seem as such?Zenia
S
51

I don't have studies, but I will relate my experience.

I find that horizontal scrolling is tedious when dealing with text. I look at the environment that the code will be used in, and set width standards based on that context.

For example, when I worked in Emacs on XWindows, it worked well to have 2 Emacs windows side-by-side at all times. That limited them to 80 characters, so that was my max line length.

At one point I worked in Visual Studio on a 1920x1200 screen. I'd keep it maximized, with all tool windows docked down one side. There was enough space left for two editor windows side-by-side at around 100 characters.

I also find that the longest lines come from method calls with long parameter lists. This is sometimes a code smell: perhaps the method should be refactored.

If you & your co-programmers have high-resolution screens and sharp eyesight, by all means use a small font and long lines. Conversely, you may need short lines.

Shea answered 23/2, 2009 at 15:53 Comment(2)
plus one for the "sharp eyes" because really that what happened with me.Incalescent
The exception where horizontal scrolling should be tolerated is for constant data tables, to avoid rows spanning across multiple lines.Revisionism
R
40

I normally use 120-150 unless the company describes otherwise. However it depends also on the kind of code:

  • I (almost) never use multiple statements on one line
  • I only use long lines (>12) only if lines that look similar can be aligned and not broken.
  • I always use enough spaces/parenthesis etc
  • I prefer longer variables names above shorter names

Until a few years ago I limited to 100 but now widescreens are normally used and high resolution monitors 120 can be even seen on laptops (which I barely use).

Comparing a screen to a book is not really good because a book has more vertical space and a screen has more horizontal space. I always try to keep a function max. one visible screen long.

Residuary answered 19/3, 2010 at 16:20 Comment(8)
How does 120-150 chars per line work with having multiple windows open side by side? Do you keep many code editor windows open side by side? — On my 30'' monitor, I can have 3 windows side by side, if I limit my lines to 97 chars/line.Stefa
I code on a large display and I also like larger amounts. I aim for 110-130. One of my main goals is readability and breaking up statements into 2-3 lines is sometimes less readable in my opinion. I also will sometimes go to 500-1000 to hide junk I don't want to see such as some comments, disabled code, and some hard-coded values. I think it depends on the programmer also. If most coders operate at 80 then its best to aim for that when working with shared code.Grovergroves
120-150 line-length makes it impossible to display a three-way merge window which is the most efficient way of doing merges when the team is doing a lot of code changes overlapping with each other (which is the case for most of the teams). These kinds of ultra-wide lines can be soft-wrapped but that is ultra-ugly and hard-to-read as well.Cushat
You are my accepted answer.Zenia
Was it you who commented another line length question with that point @sola? Do you spend all day every day doing 3 way merges? Have you considered changing your development workflow so that you don't have to target the entire arrangement of your screen display for 3 way merges? You must be sick of them by now.Zenia
@Zenia The necessity of doing 3-way merges mostly comes from team size. I have mostly worked in bigger teams and not often alone. In one particular big project (Liferay), we had to do tons of 3-way merges every day. In others, less so, but still quite a lot. When I work alone (rare), I do not have to do them at all or super-rare.Cushat
Thanks for explaining @sola. I feel sorry for you. I believe I do recall an increase in merges with larger teams (up to 17 for instance), but I still wonder whether better management of the work (demarcation between programmers) could reduce this. When you get to the stage where 50% of your time is merging commits you know you're close to heat death. But back to the original question - this just re-double-confirms that this is no reason to justify shorter line lengths. I can't remember the last time I did a 3 way merge and I'm supposed to set up the whole code base to optimise for that case?Zenia
@Stefa I mostly focus on 2 files side-by-side with 3 panels altogether, but I also leverage other features such as a vertical concertina that enables instant swap between dozens of files and multiple views (locations) on the same file (vim). Also tmux panel zooming for instant full screen, and use keyboard or mouse to slide dividers (vertical and horizontal) to vary dimensions for panels when viewing 3 or more files on 1 screen. vim and tmux paging also instantly slide multiple "screens" of these setups. Perhaps most GUI IDEs can't keep up at this level of performance though.Zenia
G
11

Disregarding hardware restrictions, and any differences in how we read code versus natural language, I see three primary reasons to limit lines to around 80 characters.

  1. Human eyeballs are round, not really narrow and wide, and most of their resolution is in the middle. When reading for hours at a time it is a lot more comfortable to sweep the eyes in short arcs, using one scroll bar as needed. I don't know of a formal study specific to the legibility of code, but from my own observations, with the monitor 2 feet away, with text sized at a 10pt monospaced font, 100 characters takes up about 1/3 of my horizontal field of vision, or around 60 degrees (outside of the 30 degrees or so where all our eyes' resolution is at).
  2. Most people use a large monitor at work so that they can see multiple things without clicking back and forth, not so that they can see one thing really big.
  3. Shorter lines contain less complexity, which hopefully forces a developer to break up make their code into more digestible units.
Gerianne answered 29/9, 2016 at 18:6 Comment(1)
I agree on the "see multiple things without clicking". We have the same need for visualizing a lot of data as pilots have in cockpits. IDE's do not necessarily understand this and waste a lot of pixels.Diogenes
F
9

Maybe the 80 characters is also a good point to avoid these bad getter chains:

object.getFoo().getBar().getFooBar().get ...

if you limit it to 80 characters, maybe someone would localize these variables and do null check etc, but maybe most programmers would let them wrap in the next row. i don't know

Beside that, 80 characters are great as starblue mentioned. This should defenitely goes into the coding standards.

Fellowman answered 5/8, 2009 at 5:45 Comment(1)
FYI, excessive method chaining like this is known as the train wreck anti-pattern.Corkwood
A
9

Here is a study for you:

I teach programming for more than 30 years, and during this time I accumulated 1823 source codes in C with various routines, from random small games to neural networks, compilers, educational softwares, automatically generated lex/yacc source codes, etc.

Following the Pareto Principle, 80% of those programs have lines smaller than 159 columns. So, to cut the lower 20% and the upper 20%, we have:

  • 1823 source codes
  • 80% of them smaller than 159 columns
  • 80% of them bigger than 64 columns

Now that is a range that gives you freedom. You don't want to limit your code to 80 columns just for the sake of it, because sometimes you will need nested loops, functions, or some indentation that will be easy to understand in a bigger line, and if you forcibly distort your logic to fit an arbitrary column width, you are not using the best logic.

Sometimes, on the other hand, the size of a line is an indicator that your logic could be better, and your line could be smaller; specially if you are not in a nested part of the code and you already crossed the limit of, say, 160 columns.

Based on my own experience and readability, I recommend you write your code aiming for 80 columns, but allowing until 120 columns of margin, and never crossing the 160 columns limit.

Also, we should consider the older experience of reading that exists: books. Books are typographically created to easy the reader's eye movement, and the best sized column according to professionals in the area is ideally around 60 characters per line, not less than 40, not more than 90.

Since coding is not exactly reading a book we can go for the upper limit, and we should stay between 80 and 90 characters per line.

Unless you are programming low level code that will run in specific screen sizes and old monitors, than I would recommend you follow gopher standard, which is 67 characters per line.


Curiosity:

  • the biggest line in the 1823 source codes is a quine of 1020 columns in a single line
  • the biggest line of code that is not a single line is a text adventure game with 883 lines. Of course this is good practice, because if you don't limit the break of a line, the text will be better displayed in your screen, breaking in the column you actually have as size.
  • the smallest lines of code (non zero) are 14 characters long.
  • the command I used to check the file sizes is: find . -type f -name "*.c" -exec wc -L {} \; | sort -n | less -N
Agni answered 19/2, 2022 at 5:33 Comment(9)
Are the sources student assignments? They may simply not reflect production quality code - full error handling gives a lot extra indented statements in my experience.Diogenes
To answer your question: yes, they are student assignments.Agni
That may actually be interesting - how do code change when programmers mature.Diogenes
Yep... It would be very nice to learn from such database. I guess the problem is to gather such data.Agni
Based on a word count, roughly 34% of this answer is gold... right up until the words "160 columns". Just stop there and you're good.Zenia
Another problem with studying that @ThorbjørnRavnAndersen is that just because you find the code in production in a corporate environment does not mean it is mature ;-)Zenia
@Zenia perhaps you care to provide some constructive criticism instead, like a better definition of “mature”, thenDiogenes
I'm not sure that's possible @ThorbjørnRavnAndersen. Firstly to do so "instead" would mean I'd have to go back in time and make some unconstructive criticism first. Secondly, for me to provide a "better" definition than yours, you'd have to provide a definition yourself. FYI I was not challenging your use of the word "mature". I was assuming a similar usage to your own. I was just making a humorous comment. I also found your comments constructive and useful. There's no reason that I can see to change that.Zenia
@Zenia Sorry to inform you it wasn't.Diogenes
B
4

I distinctly remember reading somewhere (I think it was in Agile Documentation) that for optimal readability a document's width should be about two alphabets, or 60-70 characters. I think the old terminals' line width came in part from that old typographical rule.

Buckling answered 23/2, 2009 at 15:54 Comment(1)
No, it didn't: ibm.com/ibm/history/ibm100/us/en/icons/punchcard ... and there's no such "typographical rule", and a rule based on the size of the alphabet makes no sense (oh those poor Chinese). And saying that you recall reading something somewhere is completely useless. Even if you did read it somewhere, so what? There's no reason to think that your source is correct/valid/authoritative ... it was probably written by the some sort of people posting their opinions here as answers to a request for studies ... papers that are based on facts, evidence, that sort of thing.Webb
F
4

The right margin option is intended to show you the width of the page if you're going to print the code, and has previous posted said it was set to 80 because that's what the line length historically was before GUI all the way back to punch cards.

I've seen a recommendation on some blog recently (can't remember what blog) to increase you IDE font size in order to improve code quality, the logic behind it is that if less code fits on screen you'll write shorter lines and shouter functions.

In my opinion shorter lines make reading the code and debugging it easier, so I try to keep the lines short, if you have to set a limit to make yourself write better code then choose what works for you - also if you are more productive with longer lines feel free to increase the page size and code only on a wide screens.

Foch answered 23/2, 2009 at 15:55 Comment(3)
being able to print code is almost a forgotten art. Being able to use a highlighter and comment in the margin is a great tool for understanding.Diogenes
The question is about studies, but all we get in these answers are personal opinions.Webb
Making your lines shorter makes the functions longer.Zenia
F
2

As some people have pointed out in other answers the reason for the 80 character limit is partly historical (punch cards, small screens, printers etc) and partly biological (to track what line you are in it's generally good to be able to see the entire line without needing to turn the head).

That said, please remember that we are still humans and we build tools to solve our own limitations. I propose you ignore the entire debate about character limitation and just write stuff that makes sense regardless of their length, and use an IDE or text editor that can help you keep track of the lines properly. Using the same argument for indentation in the tabs vs spaces debate, as well as the how wide should the indentations be I propose you use an indentation marker (most commonly the tab) and just have people configure their own IDE or text editors to display them as they find most comfortable to them.

Sticking with a fixed number of characters per line will always make things worse for everyone but the targeted audience. That said, if you will never share the code, ever; then there's really no reason to even have this discussion to begin with. Should you want to share the code, you should probably let people decide what they want on their own instead of forcing yours (or someone elses) ideals on them.

Frolicsome answered 20/5, 2014 at 18:58 Comment(2)
It's entirely historical: ibm.com/ibm/history/ibm100/us/en/icons/punchcardWebb
They have to read it, but we have to write it, @JonasLihnell, why should they have the pre-eminence? There's also a reason why some standards have outlawed tabs altogether - a reason - it's not all personal preference - that's why this question is not "opinion based" - some people use that "reason" as an excuse to close many good questions. You cannot enforce a line length to the preference of people you haven't even met yet when their preference may not even be optimal. It's incumbent on you to make a reasoned decision and demonstrate good practice to them.Zenia
K
0

To the best of my knowledge the 80 character is used as a coding standard to maintain compatibility with command line editors (default terminal width is typically 80 characters). With modern IDEs and large screen resolutions 80 characters is probably not "optimal", but for many developers maintaining readability in the terminal is essential. For that reason it is not likely that 80 character width will be replaced as the de facto standard for code width anytime soon. And to answer your final question, yes, code width as well as any other characteristic which will affect your code's readability should be addressed in your coding standards.

Kalfas answered 23/2, 2009 at 19:38 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.