views:

6029

answers:

31

This is a matter on which I would like to gauge the opinion of the community: Do you still limit the length of lines of code to a fixed maximum?

This was certainly a convention of the past for many languages; one would typically cap the number of characters per line to a value such as 80 (and more recnetly 100 or 120 I believe). As far as I understand, the primary reasons for limiting line length are:

  • Readability - You don't have to scroll over horizontally when you want to see the end of some lines.
  • Printing - Admittedly (at least in my experience), most code that you are working on does not get printed out on paper, but by limiting the number of characters you can insure that formatting doesn't get messed up when printed.
  • Past editors (?) - Not sure about this one, but I suspect that at some point in the distant past of programming, (at least some) text editors may have been based on a fixed-width buffer.

I'm sure there are points that I am still missing out, so feel free to add to these...

Now, when I tend to observe C or C# code nowadays, I often see a number of different styles, the main ones being:

  • Line length capped to 80, 100, or even 120 characters. As far as I understand, 80 is the traditional length, but the longer ones of 100 and 120 have appeared because of the widespread use of high resolutions and widescreen monitors nowadays.
  • No line length capping at all. This tends to be pretty horrible to read, and I don't see it too often, though it's certainly not too rare either.
  • Inconsistent capping of line length. The length of some lines are limited to a fixed maximum (or even a maximum that changes depending on the file/location in code), while others (possibly comments) are not at all.

My personal preference here (at least recently) has been to cap the line length to 100 in the Visual Studio editor. This means that in a decently sized window (on a non-widescreen monitor), the ends of lines are still fully visible. I can however see a few disadvantages in this, especially when you end up writing code that's indented 3 or 4 levels and then having to include a long string literal - though I often take this as a sign to refactor my code!

In particular, I am curious what the C and C# coders (or anyone who uses Visual Studio for that matter) think about this point, though I would be interested in hearing anyone's thoughts on the subject.

Edit

Thanks for the all answers - I appreciate the variety of opinions here, all presenting sound reasons. Consensus does seem to be tipping in the direction of always (or almost always) limit the line length.

Interestingly, it seems to be in various coding standards to limit the line length. Judging by some of the answers, both the Python and Google CPP guidelines set the limit at 80 chars. I haven't seen anything similar regarding C# or VB.NET, but I would be curious to see if there are ones anywhere.

+4  A: 

Now that I can squeeze the font size down to be quite small, I prefer not to place arbitrary limits on text length. I want to see as much code as possible on my screen.

Having said that, I will say that excessively long lines of code can be difficult to understand, so I make liberal use of line breaks and indentation, along with white space, to improve readability,

DOK
+2  A: 

I still stick to 80 chars wide unless I know I am the only person who will be looking at the code. Exceeding the limit is a great indicator of ugliness (e.g too much nesting, or trying to do too many things on one line).

I have a wide screen display, but I actually prefer to rotate it and use it as a tall screen - more lines of code is much better than wider lines.

It's also harder to cross-read lines when they're short.

I also like to use vim over ssh connections quite a bit, and I use a laptop with a pretty small screen at times. On those days, I appreciate my 80 column limit that much more.

JimG
+11  A: 

I certainly try to limit the length of the line (120 currently), but just for readability. I even use a trick to force myself to do it in Visual Studio:

http://blog.feradz.com/2009/02/add-line-length-marker-in-visual-studio/

As for deep levels of nesting: I remember reading coding guidelines for writing code for Linux kernel, I believe created by Linus himself. The guidelines included the maximum level of nesting in a function (3 as I remember) with the comment, that if you need more levels than 3, you shouldn't write kernel code ;)

bbmud
The line length trick is nice.
JohnOpincar
Ah, didn't know about that line marker feature - thanks for that. And yeah, I would have to agree that deep nesting in a function is a sign of something gone wrong usually.
Noldorin
That depth limit annoys me. I was working on a custom filesystem, and a couple of the treewalk algorithms needed four levels of nesting.
Joshua
If you have Visual Assist for Visual Studio, it has a line-length marker built in (see Options).
leander
@bbmud: I do the same in IntelliJ IDEA (an IDE that used to be a Java only IDE but that now evolved): I put the vertical marker reminder at 100 columns.
Webinator
+56  A: 

Normally, I don't worry about this too much, especially not to the point where I'd actually set a fixed limit. Generally, I go by the actual readability in my mind. If I have trouble reading it all on one line, I'll split it. There are a couple of instances where I (almost) invariably do this -- methods with several parameters, including when using the automatic constructor technique in C#, and chained method invocations, such as when using IEnumerable extensions. I'll even do this when line length is not really an issue. Typically in the latter case, I will split the methods on the dot and put each method on a separate line.

 var query = table.Where( s => s.something ).Select( t => t.property ).FirstOrDefault()

becomes

 var query = table.Where( s => s.something )
                  .Select( t => t.property )
                  .FirstOrDefault()
tvanfosson
Resharper is very good at this. If you set up the rules properly it will format the code like this automatically.
bbmud
Yeah, I think you've taken what tends to be the standard approach. Splitting lines with many method calls by the dots is what I also do, and seems quite sensible. Could you maybe given an example of in what case you *wouldn't* terminate the line at a certain length?
Noldorin
+1 for soft limits based on readability rather than an arbitrary fixed one.
Michael Carman
@Noldorin -- maybe a foreach with long variable names and a single IEnumerable extension method? I really don't like to split a foreach across multiple lines.
tvanfosson
@tvanfosson: I see your point... Not sure if I totally agree however, but there's undoubtedly justification for it. Thanks for your reply.
Noldorin
This is good specially when you have conditions involving long name vars and the 80-char limit will force you to split it...
+3  A: 

I set my character-length per line to 100, even then I don't reach it too often.

If you are writing longer lines of code your code is a mess. Breaking up long strings, \n and indenting long arguments for functions and so on just keeps things clean. Im sure there are some 80-char screens still in use but this isn't the main reason.

Programming is a set of short sequential statements, not long gangly ones.

Aiden Bell
Regarding long string literals, that's exactly what I normally do. I do wonder however if it's the right thing. It does seem slightly ugly in its own way, and I'm seeing others recommend against it...
Noldorin
It is ugly, but there is much worse. String literals IMHO should be kept out of code as much as possible anyway. The uglyness is punishment :)
Aiden Bell
You have a point there. I usually manage to avoid long string literals except when throwing exceptions, in which case I should probably use resource strings, but can't really be bothered.
Noldorin
+3  A: 

I limit textwidth to 80. This is because, I do not like long lines wrapping around. If a long line wraps around, it will be difficult to navigate using Vim (and possibly other editors, without using a mouse/pointing device). I will have to try n| (in Vim) where n stands for the trial-and-error column number. If the line is shorter a ^ (to go to the first column with text) and $ (to go to the last column) action will be sufficient. So, I think textwidths are relevant today too.

Just my observation.

Alan Haggai Alavi
+1  A: 

There's an option to switch on line wrapping which is most useful. Some APIs require longer lines... these include the CCR library from Microsoft and I fairly frequently unavoidably go beyond your arbitrary limits when writing LINQ and their method chain equivalents. Of course there are ways to format a single line such that they are spread over many.

spender
Not sure what you mean by "require" longer lines. I agree that code using LINQ or the CCR often requires long statements, but they can nonetheless still be broken up.
Noldorin
+4  A: 

I don't have a hard and fast rule here. Like you said, if there's a long string literal, who cares if you have to scroll to see the whole thing. My center monitor is 27.5 inches so what I like will certainly differ from what someone with 19 inch monitor will like. I don't like code that has so many line breaks that you have to constantly page up and down just to see a few "lines" of code.

JohnOpincar
That's another good point. I'm considering adopting a style where string literals can extend to arbitrary lengths, but all other lines of code are limited. Not sure I've ever encountered a situation so severe that only a few "lines" fit on the screen, however.
Noldorin
This was a case of someone putting each actual parameter on a separate line, lots of useless comments, and one or two blank lines between almost every actual "line" of code. It was very frustrating to work with and I ended up using an auto-reformat on it just to get it back to a reasonable state.
JohnOpincar
@JohnOpincar: Oh, that's pure horribleness. Whenever I find myself using such code written by someone else, it makes me cringe - it's a false sense of readability to some people, it seems.
Noldorin
what if you have a big monitor and someone else in your team is working off a laptop?
Paul Rowland
+4  A: 

Limit to 80 characters. The Google cpp coding standards have a good explanation why, but my main reason is the "parallel editors" one.

(Edit: look up "Line Length" in the google link, failed to direct-link for some reason)

FeatureCreep
+2  A: 

Virtually all the time I work on code, I have multiple windows open. Documentation, other parts of code, diff output, reference websites. Limiting myself in code width means I can organize windows side-by-side, instead of having to alt-tab through them (which can get confusing as hell).

That's my #1 reason for limiting line length. Not having to scroll horizontally is another convenience.

DevSolar
Enable line wrap?
spender
Having wrapped lines screw up your indentation?
DevSolar
+54  A: 

I still limit lines to 80 characters:

  • This way I can view three files at the same time, each in a column side by side. (This proves especially useful when doing a three-way merge.)
  • I'm sure the code will be readable when I print it or put it on a web page.
  • It's the standard limit for Python code.
Bastien Léonard
May I ask why would you read three files at once? And why would you ever print code? If anything, it makes it easier to copy to a blog...
Kobi
When following a program's flow I often have to go back and forth between the same files. I'm using Emacs so one of the columns may be a shell, a class browser, a debugger window or anything else. I print code when teachers ask it (it happens quite often). Indeed it's useful for web pages too. I've added this to my message.
Bastien Léonard
When performing a [three-way merge](http://en.wikipedia.org/wiki/Merge_(revision_control)#Three-way_merge), nothing beats being able to view (all of) all three files side by side.
Jon-Eric
Your point about being able to view multiple files along side each other is a very worthwhile one. I'm not convinced printing is a terribly important reason, but that could just be because I personally don't often find the need for it.
Noldorin
In my opinion, one should balance a three-way merge vs. reading or writing one file at a time. If you spend all day merging and you are in charge, fine, declare a limit. Most projects would probably benefit from no limit, seeing more code at once.
jhs
@Bastien Léonard: on my single 24" 1920x1200 screen (which is by now an uncommon setup, there are developers with 2 or 3 24" and even devs with 26,27 [all these new iMacs] and 30" screens) I can 3-way merge up to 100 columns on the same screen with room left left and right. Interestingly, I put the "reminder" vertical line at precisely 100 columns :)
Webinator
Exactly. I can even compare two 120-column documents on my monitor, while I still agree that for printing it's good to have limit at 80. I put three limiting lines to Visual Studio editor at 80th, 100th and 120th column. I try to break at 80, but if it makes sense I write code until 100 and in rare cases even until 120. I try to avoid writing code longer than 120 columns.
Sergiy Byelozyorov
I stick to 80 mainly out of convenience. Using eclipse, with the overhead of having the file tree on the left, I can fit exactly 2 windows side by side and see all the code. Once I switch to a bigger monitor, I'll probably reconsider. (My laptop monitor is 1680x1050, btw)
Chimmy
+3  A: 

Using my crappy old LCD monitor in portrait orientation enables me to view two files side by side with more than 120 lines visible at a time.

In gvim, textwidth=74 for all code.

Sinan Ünür
+3  A: 

Two reasons why I stick to 80 columns wide for my source:

  1. Remote editing, often through an SSH session, and particularly on windows with something like putty. Even in this day and age, its sometimes difficult to actually get more than 80 chartacters.
  2. comfort. With shorter lines, I can set the size of the text quite large, and then I can stare at the code for a long time with neither eyestrain nor backstrain (from leaning forward in my chair). When I need to see a bit more, I temporarily zoom out and usually open three more editors to see what's calling what.
TokenMacGuy
+5  A: 

I usually cap around 100 columns of code.

My rule of thumb is, If I can't fit it onto my screen without horizontal scrolling, reformat.

If I'm doing something likely to be printed, I will format to fit printed material.

Paul Nathan
100 lines of code should say 100 columns
Photodeus
+2  A: 

The effect of indents could have an impact on maximum line length.

If tabs are used for indenting code you sometimes have to consider people may be viewing with a different number of chars/tab.

Sometimes after a couple of indent levels an 80 or 100 character limit can result in the actual space for code being reduced a bit.

Of course too much nesting isn't ideal but is often unavoidable (exception blocks, nested loops).

On idea is to have something like an 80 char limit but only start counting from the first non-whitespace character in the line - so each sub-block of code can use an optimal amount of screen real estate.

As many comments here have stated - it's all about readability.

Bing
That's an interesting criterion you've proposed there. It would probably solve some of the issues with fixed maximum length lines, though it does of course lose the advantage of not having to scroll across.
Noldorin
+11  A: 

Something nobody mentioned is email. If you send code snippets via email or post them in a newsgroup it is good if you can prevent line wrapping. If the lines in your code are already shorter than 80 characters you don't have to reformat them.

Another thing: No matter what your convention is, stick to it. Nothing is worse than unnecessarily reformated code, because this makes diffing a nightmare.

bbuser
I think this is one of the primary reasons there's a hard limit in the linux kernel coding style guide...
leander
This argument actually justifies the 72-character wrap I sometimes like to use. (That allows several email responses), and has the nice side effect of allowing me to keep several files open side-by-side on my screen. (24" screen oriented _vertically_).
Arafangion
+6  A: 

I try to format my code to fit readably in 80 columns. (I use chiefly Java and Python with 4 spaces per indentation level.) On balance, I consider it a win for readability. I also do it for tooling reasons:

  • it leaves plenty of space for outline views, project trees and other dodads in eclipse.
  • I can fit 160 columns across my 1024 pixels using my favorite font, so I can get two documents on the screen at once on my netbook this way.
  • svn blame is easier to fit onto the screen if the source lines aren't already pushing the limits.


Complex deeply nested expressions are a problem, of course. I try to break them across lines in a way that does not impede readability, or simplify into a sequence of simpler expressions using a temporary variable.

Recently I find myself using end-line layout more (Emacs makes this easy). I was "against it" for many years stemming from reading the first edition of Code Complete.

some_variable = some_function(foo,            // an exaggerated example of
                              bar(one, two),  // end-line layout
                              baz);

I guess, what it boils down to is that I've come to view code layout as a two-dimensional layout problem. I try to use vertical alignment to communicate the structure of my code when it seems sensible. Yes, this can conflict with 80-column rule, in which case line length has priority and I revert to a more conventional layout:

some_variable =                         // for assignments that are too long, tend
    some_function(foo, bar(one, two),   // to leave the target variable on a line ending
        baz);                           // with the assignment operator.

I find that automatic code formatters, like the one built into Eclipse make complete hash out of my code regardless of how I configure them. If they break expressions, they do so in a way that is deeply mystifying and use indentation that hinders readability more often than not. And have you seen what most code formatters will do to use of "fluent" interfaces? I won't touch them.

builer().addChild(1)
        .addChild(2).withColor(BLUE)
        .metaInformation().addEntry("foo").withValue("bar")
        .build();
====>
builder().addChild(1).addChild(2
   ).whithColor(BLUE).metaInformation()
             .addEntry("foo")
                       .withValue("bar")
                                                 .build();
//... or something similarly atrocious.

This is also why I find the idea that the solution to differing code formatting preferences on a team is to have tools format to personal preferences on checkout and then format back to standard on checkin to be completely wrong-headed. Anyone who cares so little about code formatting as to be satisfied with the garbage an automatic formatter produces, should just get with the program and conform to a common style agreed upon by the team.


Years ago, when I programmed mostly in Oberon, my approach was completely different. Oberon is traditionally programmed in a styled text editing environment with proportional fonts using real tabs for indentation. This makes games with vertical alignment fairly pointless. (Though you could do some cool stuff since you have all the formatting possibilities of a simple word processor at your disposal including the ability to set your own tab stops, embed tables, graphics and other elements.)

bendin
for eclipse formatting, add "//" (without ") at end of line to force the formatter to keep these line on code on different line
Frederic Morin
Thanks, that's a useful overview. I'm not sure I much care for the end-line layout, though. It is quite interesting the F# (at least the light syntax) actually enforces such practice.
Noldorin
+4  A: 

In a reasonably condensed lannguage like C or C++ I'll cap it to 80 character line widths.

I also prefer doing indentation with tab.

I understand the need to be able to view code at 80 width, but I'm willing to pay a price to get it: my rule is it must fit on 80 width at with tabstops set to 2. Most people use larger tabstops.

In .NET or Java, where standard library class and function names are so long, and "overhead" indentation easily ends up three levels before you even start, it's a losing battle.

Joshua
+1  A: 

I don't try to limit the line length unless it gets too long. (As in sticking over the edge of my widescreen monitor... ;P)

However, the main way I do so is by writing lines like this:

ConfigDir = Path.Combine(
    Path.GetDirectoryName(Application.ExecutablePath),
    "Config"
);

Which also provides easy readability.

MiffTheFox
+1  A: 

Int32 padding = 25; Int32 lineLength = Screen.AllScreens[ActiveDisplay].WorkingArea.Width - VisualStudio.SolutionExplorer.Width - padding;

Most of the time I generally cut off my lines when they hit the edge of the scrollbar, -~25 pixels or so.

I will also condense long methods with a lot of parameters by putting a new parameter on each line, indented of course.

I will essentially fill up the editor window until it spans the monitor width. As for printing, doesn't really matter, if you print from Visual Studio it has the nice linebreak arrows it displays

David Anderson
+1  A: 

I do not limit the line length as most editors support breaking up the line per the users preferences if they want to wrap or not. Personally I run 3 monitors so I have the space. If I format it for the user, then it is sort of forcing them to view it how I want, not how they want.

Raymond
A: 

Unless you want to print it out, the only reason you would want to have a line limit would be to be able to display two files side by side on one monitor. I can't imagine doing that so I would scrap the requirement.

tomjen
I bought a new 22" so that I could have two files side by side! It's like having two screens!
too much php
+1  A: 

I try to limit my lines to 80 chars, but if I exceed for some reason, I don't make big deal out of it: most people have windows a lot larger than 80 columns, so that won't bother them too much anyway.

gnuvince
+1  A: 

I split windows horizontally into two in Emacs, so i have to limit my line length within 90~100 characters still

ZelluX
+2  A: 

Unfortunately, I routinely have to deal with legacy source code where in a few cases there is a single line of source code that is more that 3 THOUSAND CHARACTERS WIDE! Seriously.

These long lines are almost always C++ constructor functions, in the form of:

SomeClass::SomeClass( int a, int b, string c, double d, string e, double f ) : SomeBaseClass( a, b ), m_c( c ), m_d( d ), m_e(e), m_f(f), m_g(), m_h( a * e ), m_i( f*e ), m_j( c + " " e ), m_k(), m_l() { }

except with longer parameter names and longer member variable names and more of them.

In cases like these, a simple maximum column width rule doesn't help at all. At least not after the fact.... The problem is that the class has too many concerns and that refactoring needs to occur... badly. I guess that if the rule of a maximum line width of 80, 120 or even 160 bytes were given, it would somehow compel the original programmer to realize that something deeper is wrong.

jdkoftinoff
That's genuinely horrible. I can't say I've ever seen something close to that bad. What surprises me more is (even without a limit) that it didn't start ringing bells for he coder.
Noldorin
+1  A: 

My text editor (geany) has a reference line that you can set, I think the default is 72 characters. I do not line limit to that, but at the same time dont go crazy long either. If/when code is cut and pasted into bug report software or emails it gets wrapped so that is more of a driving factor than anything else for me.

dwelch
+2  A: 

Yes, i do. We prefer limited line length because we also develop at our customer that has smaller monitors and we don't want to change the sourcecode there. Therefor we limit the length of our code.

We also limit the line length in our unit tests for the same reason.

crauscher
+1  A: 

I let resharper autoformat my code. You can set your maximum line length and it will split llines bigger then our limit. Default it is set to 120 characters.

You can also visualize the border to give you an idea when your lines are too large.

Carra
Thanks. I realy ought to check out Resharper one of these days.
Noldorin
+1  A: 

Not out of any sense of tradition, I typically stick to 80 chars per line to make it more readable. It's the same principle as limiting line-lengths on a website - studies prove that people struggle to effectively read longer lines.

That, plus, I like to have my code open over the top of a web browser so I can easily scan across any docs, (or more likely Twitter/Facebook... :s)

Gary Chambers
+2  A: 

What nobody (at-least the top voted ones, that I read) seems to have pointed out is this:

Most of the lines of code are under 60 columns. There are occasional cases (<5% of lines) where the code extends beyond this normal limit.

If you have a few lines over 120 chars, either of this will happen:

  1. The editor displaying the code will consume entire screen, even tho' the code in the second part of the screen is there in just a few lines. It reduces the amount of code U can see on the screen at once.

  2. The editor is in the wrap mode and arbitrarily, at the end of a particular column, split the code to next line. It makes it hard to read.

Either way, you are interrupting the programmer from the flow.

Lakshman Prasad
Point 2. isn't a problem in Visual Studio. I agree that arbitrary splitting of code onto multiple lines can at times make it ugly, which is why advocating sensible manual formatting is advisable in my opinion.
Noldorin
+3  A: 

I try stick to 80 wide, and I try to limit my nested functions within the same command.

There's nothing more irritating than following a stack trace to find the source of the Exception is line 23, which goes on to read as:

23: Object myObj = ob1.kenobi().speak().scratchMyAss().getLightSaber().jediMindTrick();

Great, now which method call on line 23 threw the exception?

crowne
Good point regarding the stack trace... I hadn't thought of that one!
Noldorin