
Line length in programming - cjk101010
http://ck.kennt-wayne.de/2014/feb/line-length-in-programming
======
yeukhon
Here is what I've said about 80 char in the past.

"If the argument for expanding to 100 or more is that screen is getting wider,
then the benefit of wide screen is the ability to fit multiple terminals in
one window. For normal workflow, I'd split my windows into two or terminals,
depending on what I am doing, so I don't see any benefit in increasing the
limit."

~~~
aleem
Touche. Multiple monitors and more screen real estate has been proven to
increase productivity. It's an easy win.

If the lines come out too long too often, it may be a symptom of other
problems.

    
    
      if ((browser.OS == 'win') && (browser.userAgent == 'IE')) {
    

is often better written as:

    
    
      isIE = (browser.userAgent == 'IE');
      isWindows = (browser.OS == 'win');
      if (isIE && isWindows) {
    

It's self-documenting and reads like natural english. It also has the good
side-effect of making lines shorter, more terse.

~~~
collyw
Its more code, more variables. I sometimes do this with complex conditions,
but for your example I find it counterproductive.

~~~
yeukhon
Well if this is deep deep down in a nested loop, then either you increase char
or you wrap that code into multiple statements. It would be counterproductive
if this is first or second level.

However, I think I missed one important point. If you are writing for Linux
kernel, then 80 chars is definitely not enough since 8 spaces = 1 tab in
kernel code. That is, if you have a deep branching, then after 2-3 levels 80
chars wouldn't be enough. But increasing to 100 is only going to help for an
extra level.

So the important point missing is the char limit is often project coding style
dependent.

------
weland
I'm surprised and, to some degree, annoyed at the superficiality of some of
the arguments in this debate. Like this one:

> Readability - You don't have to scroll over horizontally when you want to
> see the end of some lines.

It's not having to scroll horizontally that bothers me with long lines. My
monitor is wide enough that it can probably hold 250 characters with ease. _It
's having to read long lines_. Something is very bloody, terribly wrong in
your code if you consistently find you need to write 150-character lines.

Besides, yes, monitors have gotten that wide that it's not an issue. Is there
any serious reason to assume that code is the only thing I want displayed on
my monitor at a given time? In a single window? That's as big as the monitor?
The only moment when people had a good reason to be enthusiastic about that
was the late 70s, when serial terminals appeared and teletypes began going the
way of the dodo.

Also, who says the IDE is the only place where I want my code to be output?
Maybe I want to grep on it or whatever. On an 80x25 terminal window because
the least useful thing on earth is a huge monitor where I constantly alt-tab
between a full-screen editor and a full-screen terminal.

~~~
randallsquared
"Something is very bloody, terribly wrong in your code if you consistently
find you need to write 150-character lines."

Not necessarily.

Most lines are below 80 characters, but there are good reasons (for
readability!) to use longer lines from time to time: vertical space is more
precious than horizontal on modern screens, and the more content I can fit
into each vertical page, the faster I'll understand what I'm looking at.

The main reason I like the ability to occasionally have a 150 or 180 character
line is akin to code folding, which some editors have as a feature. The
feature allows you to hide a function or class by collapsing it into one line,
because you want an overview of the code around it or calling it, and for the
moment the implementation details aren't relevant. Now, I don't actually use
the code folding feature in practice, mainly because I find that the times I
would want to use it are times when I nearly _always_ want to fold the code,
and in a case like that, it's nice to be able to "pre-fold" it by putting it
all on one line.

For example, if not using an ORM, I might want to use SQL to grab some results
from a db (in a model, say), and I almost never want to think about my SQL and
my surrounding code in the same context. Now, you might say, "Just put that
SQL in its own method with a reasonably short name, and call it where you
would otherwise have a long SQL string, and in the function that returns it,
you can break each line at 70-80 characters," but that seems like a "solution"
which improves nothing in my typical reading of the code, and requires me to
jump around to find the SQL in the rare case I need to pay attention to it. It
breaks up something which is naturally local and specific to this place in the
code.

Another example which happens somewhat more frequently for me is when I want
to use a literal object in JS. If I want to keep the definition local --
because, perhaps, nothing outside of this function ever needs it -- my choices
are to put each key/value pair on its own line (easy to find a given key, but
consumes lots of vertical space), to put multiple key/value pairs on each line
to fit ~80 characters (both moderately difficult to find a given key, and
still eats moderate amounts of vertical space), or to "fold" it all to one
line (consumes the minimum vertical space, with the trade-off that it's
difficult to find a given key). The most common case of this is where I have
the choice between using 4-6 lines, or one line, and it's an easy choice for
me to pick one line, though I've never encountered a coding standard that
agreed with me.

~~~
weland
> Now, I don't actually use the code folding feature in practice, mainly
> because I find that the times I would want to use it are times when I nearly
> always want to fold the code, and in a case like that, it's nice to be able
> to "pre-fold" it by putting it all on one line.

IMO that's just compensating for the inadequacy of tools by making code harder
to follow. Usefulness of code folding (and what it says about the code it's
folding) aside, this is a really poor solution. If you just need that done
temporarily, why not _temporarily_ replace all the returns in the region you
select, and then add them back when you're done? Any editor with search-and-
replace can do that.

> For example, if not using an ORM, I might want to use SQL to grab some
> results from a db (in a model, say), and I almost never want to think about
> my SQL and my surrounding code in the same context. Now, you might say,
> "Just put that SQL in its own method with a reasonably short name, and call
> it where you would otherwise have a long SQL string, and in the function
> that returns it, you can break each line at 70-80 characters,"

No, what I might say is "just stop thinking about the SQL query and the
surrounding code in the same context".

Alternatively, put the SQL query in a separate function that conveys some
meaning related to its purpose, so that people who read your code later don't
have to decipher a 300-character query line in order to understand what that
code is doing. They may not even be debugging that part of it, maybe something
several layers of abstraction above borks and they end up in that part of the
code debugging it.

> (easy to find a given key, but consumes lots of vertical space)

which can be easily averted with code folding? Or by simply scrolling _down_
to the body of your code. Skipping entire lines is very easy, it's following a
hundred-character snake that sucks.

~~~
collyw
> IMO that's just compensating for the inadequacy of tools by making code
> harder to follow.

Thats pretty much how I would describe the 80 character rule for old
terminals. I find the occasional long lines can make things more readable. It
certainly helps in locating the bit of code you are looking for when you can
recognise it's shape.

------
Nursie
80 is too few. The old reason for it (what if you get stuck doing an emergency
bugfix using vi on an 80 char display?!?) no longer holds.

It's not massively too few, and most lines never get close to the limit
anyway, but the odd line of 100-120 thrown in really isn't a problem on a
modern display.

~~~
NateDad
That is a straw man. No one actually thinks 80 character displays are the
reason to use 80 characters.

I think 80-100 is fine. More than 100 and you probably need to refactor the
line some, because you probably have too much logic on a single line (or you
need to choose names that aren't hugely long).

~~~
Nursie
>> No one actually thinks 80 character displays are the reason to use 80
characters.

Err, yeah they do, I have been given exactly that reason on a few occasions,
generally by older engineers who had experience with old-school machines that
had precisely those screen dimensions. I don't disagree with your main point,
but it's really not a straw man.

~~~
NateDad
Well, for most people it's a straw man. I've worked with some greybeards, and
they are smart enough to know that they can resize the terminal on their
modern laptop :)

------
matthewmacleod
80 chars is a useful rule of thumb, so long as it's tempered by practicality.
I've worked on projects where the limit was taken far too literally, which
results in code that's harder to read.

This is especially true if you're using something verbose (Java, Objective-C)
or whitespace-sensitive (Python).

~~~
masklinn
I've never had much issue keeping Python code under 80 columns. Going beyond
usually means you've used way too many nested clause and should either rewrite
the whole thing or extract part of its to subroutines.

~~~
shadowmint
Really?

    
    
        class Engineer(Person):
            __tablename__ = 'engineers'
            __mapper_args__ = {'polymorphic_identity': 'engineer'}
            engineer_id = Column('id', Integer, ForeignKey('people.id'), primary_key=True)
            primary_language = Column(String(50))
    
        12345678901234567890123456789012345678901234567890123456789012345678901234567890
        ^^ Line length marker
    

Woops. 2 characters over. Do we really need a line break there?

Guess perhaps I should rename my columns with more obscure names like engnr_id
instead.

Seriously; you see this in python all the time; people not wanting to break
the line because its only a character or two off, and then stupidly renaming a
variable to some obscure abbreviation instead.

We won't go into the 2-character indents argument, or the push for the 100
character limit that the BDFL veto'd for the PEP8 revision; but... safe to
say, I think a fair number of people hit this as an issue.

I don't think 'you can just refactor that to be shorter' is really a solution
in all circumstances.

~~~
masklinn
> Really?

Yes, really.

> Woops. 2 characters over. Do we really need a line break there?

 _You_ do what you want.

> I don't think 'you can just refactor that to be shorter' is really a
> solution in all circumstances.

You don't think the solution I didn't advocate as a cure-all in the first
place is a cure-all? Am I supposed to be surprised at this finding?

~~~
shadowmint
Well, you specifically said that if someone had gone beyond the 80 character
limit, its probably because they needed to rewrite / reword / subfunctionize
something. If you've never had a problem with it, dare I ask, how are you
qualified to make that call, given you've never had to face that challenge?

Anyway, that example is _straight_ from the sqlalchemy examples, which is
arguably (other than the extremely wordy Zope) most commonly used python orm
around.

Wordy database interaction is really common point this sort of thing, and it's
hard to refactor/rewrite your way out of it; that's the only real point I'm
making.

I personally think strict adherence to line length limits reduces code
quality; you've got to use common sense for it.

~~~
masklinn
> Well, you specifically said that if someone had gone beyond the 80 character
> limit, its probably because

Yes. The operative word here is "probably". Meaning not always.

> If you've never had a problem with it, dare I ask, how are you qualified to
> make that call, given you've never had to face that challenge?

And here we can see an other important word of the original comment: "much" as
in "much of an issue". As in, I've faced it, I've never found it very
difficult a challenge to go against. Now of course if you pile on additional
constraints for personal reasons…

> I personally think strict adherence to line length limits reduces code
> quality; you've got to use common sense for it.

I have no issue with that, but common sense being a super-power[0][1] and thus
generally uncommon. Thus in my experience erring on the side of respecting
line length limits and having to defend an exception to the rule produces
significantly better results, and avoids 200+ characters lines because "well
it fits in my widescreen 24" display so I don't see what the problem is"

[0] [http://walls4joy.com/walls/people/deadpool-wade-wilson-
commo...](http://walls4joy.com/walls/people/deadpool-wade-wilson-common-
sense-9639-1280x760.jpg)

[1] and was likely named by people who had none

------
NateDad
The argument about no one editing in a 80 character terminal anymore is a
straw man. That's not the real reason 80 characters is good. The article even
says why - we're just not good at reading long lines for whatever reason.

There's two modern reasons for smaller liner lengths (80-100) besides
cognitive capacity:

Viewing/editing two files side by side on the same screen.

Side by side diffs.

Now, that's not to say that you should contort the code to make lines short.
If it makes the code significantly more difficult to read, don't do it... but
still try to keep it reasonable. This is also a good reason to keep your
variable names relatively short - so you don't hit this situation all the
time.

~~~
frou_dh
What doesn't help is silly idioms in some environments where most of the lines
written START at 2 or 3 indents deep because they're inside a method inside a
class inside a namespace that are all indented.

===

If anyone's interested, I wrote a simple command to scan files for
configurable line length violations and the presence of a file-terminating
line ending.

[https://github.com/frou/pagecop](https://github.com/frou/pagecop)

(yes, I'm aware it could probably be duplicated with some sed/awk wrangling!)

------
mrottenkolber
I found 72 character wide lines to be optimal (writing CL). Note that I also
apply the rule of choosing long descriptive symbol names. E.g. MAKE-RESOURCE-
RESPONDER etc...

When I have trouble keeping the lines short I consider: 1) Is there a better
way to write this? 2) Is this function too big?

There are cases where lines have to be longer, but not in Lisp. Inability to
write short lines is a symptom of bad syntax designs like e.g. C et al.

EDIT: I have been writing JS the last months and keeping lines short is
especially hard in JS, because of its abomination of a syntax. UNIX style
backslash escaped line breaks don't help either.

------
nkuttler
I'm glad we talk about this. Once we have solved this question we can move on
to really important stuff, like tabs vs spaces.

~~~
mooism2
Code is read far more than it is written. Therefore code legibility is
important. Line length affects code legibility. Therefore line length is
important.

~~~
sparkie
Code can be read in more ways than one. More often than not you aren't
interested in all the minor details in a single statement, but you're
interested in the larger structure of some code unit (say, a function), and
having dozens of wraps in a function hinders the ability to scan through the
code vertically. Therefore, line length is unimportant.

------
arocks
In my opinion the 80 character limit is mostly for better presentability. If
the code appears in a blog post or a book, it is better to read and typeset if
it is less than 80 characters. Though there are several articles[1] which
explain other reasons for this legacy limitation.

I would be happy to read code more than 80 characters, if it doesn't have to
be artificially cut into multiple lines (the screenshot in the post is a
pretty good example). In fact, I find 80 characters too less and often set
Emacs to use 100 characters as the limit.

[1]: [http://stackoverflow.com/questions/903754/do-you-still-
limit...](http://stackoverflow.com/questions/903754/do-you-still-limit-line-
length-in-code)

~~~
mooism2
IMO, given that most blog templates include copious margins, many don't allow
readers to resize the text, and some don't even allow readers to scroll
horizontally, 80 characters is far too long for a line of code in a blog post.

~~~
arocks
Sadly true. In this age of Responsive design, figuring out an optimal line
limit for code samples is a tricky task indeed.

------
adamtulinius
And obviously practicality can get in the way. 80 character lines will be a
nightmare in a java-project with verbose naming schemes
(FactoryFactoryObjectThingymybobProducer thingy = new
FactoryFactoryObjectThingymybobProducer(..);).

~~~
viraptor
Or python if you're already in a function in a function in a class (so 68
chars left). If you also standardised on importing modules, not classes things
can get silly. My favourite counter-example to the 80 char limit was a line in
openstack which was:

    
    
        return some_loaded_module.fairly_descriptive_but_necessarily_long_name(not_very_long_argument)
    

The way applied to fit it without forced line breaking?

    
    
        fdbnln = some_loaded_module.fairly_descriptive_but_necessarily_long_name
        return fdbnln(not_very_long_argument)
    

(yes, actually using first letters of words) Because yeah... that makes things
simpler than just crossing the limit in that place.

~~~
mst
In perl I'd just write -

    
    
        return $some_loaded_thing->fairly_descriptive_but_necessarily_long_name(
          $not_very_long_argument
        );
    

Surely python has something approximating an equivalent?

~~~
collyw
Come on, you can get rid of the return statement if it is the last line in a
subroutine.

------
keithgabryelski
I disagree with the author that the programmer can't interpret longer than 80
lines. we don't read programs like a 6 year old sounds out words. We read more
like a 10 year old (and above) by sighting tokens.

Simply put: the world is different than it was in the 70s and 80s and 90s (all
decades I have programmed in).

1) screen width is generally wider 2) screen widths are generally exandable 3)
identifiers are generally longer

In today's world I see little reason to hold to the 80 character limit causing
line breaks in what would other-wise be odd places.

That all being said, we still have yet to realize an editor that displays
source code in a programmers preferred spacing while saving the program in the
repository's preferred spacing. THAT is the real issue, here -- that editors
are not helping with this issue, wrapping and indenting code as the screen
width allows.

Your primary concern, with line-length, should be readability -- if your group
decides 72 characters is the limit, well, so be-it, but I would press anyone
who believes that is acceptable for JAVA.

And I no longer see a reason why one line length limit should hold for all
source files. Why not let the source code decide the best line length -- we no
longer have fixed sized screens, these are windows that expand with click and
drag.

~~~
collyw
That's a far more sensible response than the OCD like attitudes of some
commenter’s here.

------
bjourne
I think this post was upvoted because the tip is easily among the top 10
advice that can be given to aspiring programmers. Forcing yourself to write
short lines forces you to decompose code which in turn lets you see the
patterns you are working with which you then can refactor. Long lines, deeply
nested code blocks and code duplication. Those traits tend to cluster together
and are a sign of inexperience imnsho.

------
logicallee
Most languages allow you to be quite concise. The best argument for 80
characters might be that it keeps you that way.

A similar thing would happen if technical writing and scientific reports kept
the average sentence to 12-15 word sentence averages and tried not to go over
25. Reading comprehension goes up:

[http://www.onlinegrammar.com.au/how-many-words-are-too-
many-...](http://www.onlinegrammar.com.au/how-many-words-are-too-many-in-a-
sentence/)

It's very similar. Breaking one long sentence into two is the same as breaking
nested if and loop statement into several lines, the first just assigning a
boolean based on the test. Then the if test just tests the boolean. Reading
comprehension goes WAY up.

Look at the top response on this question:
[https://news.ycombinator.com/item?id=7289087](https://news.ycombinator.com/item?id=7289087)
(the one with several short lines.)

100% comprehension.

~~~
collyw
I just had a quick look at that grammar article. I imagine when people are
describing something technical / scientific / difficult to comprehend, it will
take more words.

~~~
logicallee
And what is more technical than code?

It's literally logic that will be followed extremely, anally literally. No
scientific language gets close to being that literal - normally, you are
always going to keep the author's view/point in mind as you read. If you were
to accidentally remove a random "not" from scientific writing (as happens), we
can usually realize what the author meant. (With rare exceptions, if we are
particularly unfamiliar with the topic.)

With code, on the other hand, code doesn't have a "point of view". It will
just do whatever you wrote, completely literally. The shorter the expressions,
lines, etc, the better.

~~~
collyw
Code rarely has the ambiguities that spoken languages do.

------
scrabble
I put two guidelines in my editor. One at 80 chars and one at 100. I treat 80
like a goal and 100 as a hard limit. If I go over 100, I'll put the break
around 80.

Not only do I find the code easier to look at, but I find I write better code
and I'm less likely to violate the Liskov substitution principle.

~~~
NateDad
Wow, I do the exact same thing. Nice to see someone else doing the same.

------
zk00006
Under what mechanism is it decided that this particular post becomes visible
on Hacker News? Does it simply mean that one user with high karma liked the
post? The 80 character rule is in programming over and over again and I didn't
find anything new in the article...

~~~
mooism2
The information on how to configure emacs to highlight lines that are too long
was new to me.

I presume it is on the front page because it has got several up votes in its
first half hour.

------
eddd
Never ending stories \- tab vs spaces \- line length \- republican vs
democrats \- favorite colors

~~~
zk00006
exactly, however, when you point this out, the "cool" community votes you down
quickly :)

~~~
collyw
pedantic OCD community

------
frou_dh
Before we start I'd like to point out that I have a few cans of mauve paint
going spare.

------
chrismorgan
In Vim:

    
    
        set textwidth=80 colorcolumn=+1
    

Then you get a coloured column 81 (probably red).

For some things I use colorcolumn=+1,+21 for highlighting 81 and 101, for
situations where I allow myself 100 in an extremity.

------
Sirupsen
To highlight characters after the 80th column in Vim:

    
    
        match Error /\%81v.\+/

