1. 46
  1. 23

    I think this is one of those personal issues where people will never agree. I think the most important issue is not so much what is better – that’s very much a personal issue which depends on personal priorities – but rather what works best for everyone in the team, and then stick to that.

    I’ve found that something like “wrap between 80 and 100 when feasible, and maintain a hard limit of 120 characters” is often a reasonable compromise that works well for most people (but it depends a bit on the team and code base).

    Unfortunately, I’ve had to deal with far too many assholes who insist their personal preference is superior and insist everyone on the team with inferior preferences submit to their superiority :-( Developers can be so toxic.

    1. 6

      Lines that go too far out probably should be refactored at some point. I’ve often found for example that very long if statements are often indicative of missing intermediate variables/functions that would be better at demonstrating intent.

      1. 3

        So, writing a Python unit test with the default convention of 4-space indents:

        8 characters indentation for the test-method: Remaining 72, then one one line for example an assert statement self.assertEquals(, ): remaining 50 characters (including a space after the comma).

        This gives 25 characters each for two variable names for example, for this it is enough.

                self.assertEquals(due, expected)
        

        Yet, even simple literal expresssions require the introduction of a local variable. Asserting in a loop or conditional branch or a with block, etc. will even reduce the space. The style the 80 character limit pushes codebases into is littered with local variables. and it often does nothing to improve any kind of readability of the code. It just trades in horizontal space by wasting vertical space.

        I don’t like the notion of that is often given of source code being a text, as if it was a newspaper article where a strong column-limit improves readability. Rather we are writing out trees in text form, and well, if we hide that tree structure by variable assignments, we don’t improve our understanding of the syntax tree.

        1. 1

          I think idiomatic Python style itself has a preference for local variables over nested expressions. If you look at Lisp code, you’ll see immensely nested trees—usually limited to 80 characters, but taking up multiple lines. Random example: org-list.el.

          Of course Python also allows this:

          class Test:
              def test():
                  self.assertEquals(
                      get_value(
                          do_stuff(1 + thingy(self.stuff)),
                          value_source.frob_everything(
                              params.FROB_FACTOR * (
                                  params.FROBBINESS + (1 - self.alpha)))),
                      7)
          
    2. 8

      The line is lava:

      set colorcolumn=81
      highlight ColorColumn ctermbg=Red
      
      1. 3

        I do something similar:

        fun! s:color()
        	highlight SoftWrap cterm=underline gui=underline
        	highlight HardWrap ctermbg=225 guibg=lightyellow
        endfun
        call s:color()
        augroup softwrap
        	autocmd!
        	autocmd Colorscheme * call s:color()
        
        	" I don't know why this needs to be in this autocmd, but sometimes it won't
        	" work if it's not.
        	autocmd BufReadPost,BufNew *
        		\  call matchadd('SoftWrap', '\%82v')
        		\| call matchadd('HardWrap', '\%122v')
        augroup end
        

        The idea is that column 80 is an unobtrusive “soft wrap”, whereas column 120 is a more obtrusive “hard wrap”.

        1. 2

          Additionally, gq in vim to automatically wrap lines.

        2. 7

          We recently switched to 160. It has only been a positive, IMO

          1. 5

            160 is way too wide IMO. If I can’t vertically split 1920 pixels at a reasonable font size, I’m going to be unhappy. I consider 120 to be a hard upper limit and 100 to be more friendly to people who have slightly compromised eyesight. I just tested and I can fit 135 characters in each split, but I use a fairly small font and a very graphically minimal editor setup.

            1. 1

              We have the benefit of being a small team all running the same hardware, and everyone runs the editor maximised. I’d say in general our lines are under 100. The practice before was to add a tslint ignore before the long line, which was the worst of both worlds.

            1. 4

              At $dayjob we changed our python codebases from 80 chars to 88 chars (90 chars, but lint tools configured to avoid the gutters), and most devs have changed their default terminal window sizes to at least 90 chars. Our codebase /feels/ like it has improved – awkward arbitrary line breaks have been reduced considerably. I don’t find 90 chars to have negatively impacted horizontal legibility either. Overall, a great improvement.

              1. 4

                I agree 100% with this. I’ve also found that in the codebases I’ve worked in (Java, Javascript, C#, Rust), 80 characters is just too few columns in many cases, but it’s extremely important to still have a conservative limit (100 characters at most).

                1. 4

                  You guys should totally look into Black [1] and not bother with formatting at all. Set whatever line width you prefer and let it take care of the rest.

                  This was one of the best things that happened where I work. Every python project has black run on it by default

                  [1] https://github.com/ambv/black

                  1. 3

                    Yes, we do use black on all our python projects. We just have it configured for the line length I noted above.

                2. 3

                  There is another advantage that I think nobody mentioned yet. Setting a fairly short column limit (like 80) forces you to write code that has less indentation. Example

                  maybe_candy get_candy()
                  {
                      maybe_candy mc = no_candy;
                      if(want_candy)
                      {
                          if(have_candy)
                          {
                               mc = _candy.release();
                          } 
                          else if(can_get_candy)
                          {
                               mc = get_candy_from_sue();
                          }
                      }
                      return mc;
                   }
                  

                  can become something like

                  maybe_candy get_candy()
                  {
                      if(!want_candy) return no_candy;
                      
                      maybe_candy mc = no_candy;
                      if(have_candy)
                      {
                           mc = _candy.release();
                      } 
                      else if(can_get_candy)
                      {
                           mc = get_candy_from_sue();
                      }
                      return mc;
                   }
                  

                  This is just a silly example, but if you restrict yourself with a short column width, you end up being more creative and your code ends up looking like a story vs nested logic.

                  1. 3

                    Yes, I like that too, also for properly being able to split without scrolling.

                    I must say I actually prefer 120 characters, especially in Rust, as it tends to have long(er) signatures. Less weird line breaks, code tends to look nicer this way. It fits perfectly on my 1080p monitor in Vim with no sidebars. But I usually default to 80 characters to match others.

                    1. 5

                      Hah. :P Every Rust crate I’ve ever published is fairly strictly wrapped to 79 columns inclusive. I do this mostly because of the reasons mentions in the OP, but I’ve also found it to be fairly useful pressure towards refactoring code. Reducing right-ward drift and introducing more intermediate names usually—but not always—leads to code that I personally find easier to read. Reducing right-ward drift usually means introducing new functions or writing code with early returns/breaks.

                      At work, for Go, we compromised at 99 columns (inclusive) for code and 79 columns (inclusive) for comments. We aren’t as strict as I am in my Rust projects, but it’s good enough.

                      I would absolutely love for these problems to be solved by tooling, but so far, none that I’m aware of do. The auto-wrapping in text editors sucks. gofmt gracefully ignores line lengths. rustfmt takes the opposite approach (by enforcing line length and potentially inserting or removing line breaks), but this leads to issues too.

                    2. 3

                      Sadly my primary language is Java, so this is impossible in that case.

                      1. 10

                        At least you try to keep symbol names within the 80 character limit, right? :)

                        1. 1

                          Changing the default indentation from 4 to 2 helps a lot.

                        2. 2

                          The author has a point and usually I try to stick to it when writing languages like C or C++, but I use this loosely and will not force a line which takes up 120 characters onto an 80 character line if it is just doing one thing. Same thing with java, alltough it’s nearly impossible to keep those long function names within 80 character bounds.

                          Of all languages I’ve seen, I find that Haskell is the easiest one to keep things within the 80 character limit, allthough even there I allow exceptions for cases like function a . function b . function c $ d.

                          So basically, I stick to it when I can, but allow for longer lines when it simply looks better.

                          1. 2

                            Feels to me like one of those game theory problem: “if everybody collaborate then it is better for everyone”. And then it take just one “selfish” (I use the term loosely here) person using 120 char lines and your space optimization trick is kaput. If you have a large team, vendor in some external code, or do anything that increase the entropy of your code base style, then it may be easier to just accept that lines are gonna be longer and you won’t be able to file open side by side on one screen.

                            And, as was hinted by others, some language tend to create large lines. If you code in JavaScript, add an IIFE, some function expression for your test framework, then you are a few callback deep and then need to add a if… you don’t have much remaining space to code anything. Likewise, in Java, if you use Spring and have to use some sort of “ProviderControllerProxyGeneratorFactory”, it eat up line width pretty fast.

                            That said, I also found that going with a vertical layout for my code, rather than cramming everything in a one liner, does lead to more readable code. So there is merit in optimizing for short width. I just don’t think a hard limit is necessary, or always beneficial. Better decide case by case if you ask me!

                            1. 2

                              With white space indentation at the beginning of many lines in a program, the typographic justification for line length in prose might be less relevant: the eye needs to find the beginning of the next line easily. A typical recommendation for prose is 2.5 alphabets (to account for variable width of characters), which is even below 80 characters. Line length in typography is tied to the purpose of a text: shorter lines (like in a phone book or table) are designed for skimming, whereas extra long lines in legal fine print are designed as a deterrent.

                              1. 2

                                I have tried to find good research on this in the past, but as far as I can find it doesn’t exist. Even for prose on computer screens, there is surprisingly little quality research.

                              2. 2

                                When a city wants to set the speed limit on a new road, they first measure the speed at which the cars are driving and set the speed to the 85th percentile [1]. Perhaps instead of throwing out numbers, one would measure the line lengths of the source code and set a width appropriately.

                                Myself, I still try to stick with 80 columns, but won’t stress if a line goes a bit over.

                                [1] Per a friend who has been working in city government on planing and zoning boards for the past fifteen to twenty years.

                                1. 1

                                  I just use line wrap and people can do whatever they want.

                                  1. 10

                                    The issue I always have with line wrap is that it often (almost always) wraps at an “ugly” and “unlogical” points in the code, at least for my sense of aesthetics. When you do it manually (at whatever point) it usually looks a lot better and more “logical”.

                                    1. [Comment removed by author]

                                    2. 2

                                      I just scroll horizontally and it doesn’t bother me at all. I hate excessive line breaks.

                                      1. 2

                                        Having had to fix bugs in production using my phone, I feel like both extremes need binning.

                                        I would like to be able to unpack lines and repack without fucking up the code with extra line breaks or mistouching. Keeping long lines preserves the code flow, editing it as-is is extremely fragile. Word wrap often makes it easy with the exception of indentation based languages (I make due by keeing a counter in my head).

                                        1. 1

                                          If you’re using a whitespace sensitive lang, I would use rainbow tabs to track the levels.

                                      2. 1

                                        I wonder if you could use some combination of “linewrap + gofmt” to basically pretty print code in your editor without leaving diffs.

                                      3. 0

                                        Why would 80 be optimal? Why not 90 or 88 or 103? Having a limit is a good idea, but I don’t see any reason why it should be 80.

                                        1. 6

                                          It’s a standard that’s already chosen, and fits well on most monitors, in double or triple wide editing sessions

                                          1. 1

                                            Suppose an experiment would show using 85 yields a 0.1% productivity benefit. Would there be any reason for a company to not choose to standardize on 85?

                                            1. 4

                                              The -10% productivity hit as everybody is forced to realign their desktop layout?

                                              1. 1

                                                What a study. I’d say go ahead, if it works for your company then it works for your company.

                                              2. 0

                                                That’s presumes that having multiple files open at once is “optimal”, which the author of the article claims is for him/her because of some kind of software claustrophobia..

                                                Meanwhile people have learnt this trick that computers can have more than one display, if you wish to look at more than one thing at a time.

                                                But as with spaces vs tabs or any other formatting related discussion, some people will use what works, and some people will make the wrong choice.

                                                1. 6

                                                  I learned the trick that computers can have more than one display a long time ago. I like the trick so much that I don’t just use one additional monitor, but two, for a total of 3. I even wrote my own window manager many moons ago to support it.

                                                  And I still use 80 columns. Because everything the OP said is just as true with multiple monitors as it is for one. At least, for me, anyway.

                                                  1. 3

                                                    And I have multiple screens, and multiple workspaces, with code and docs and references all over the place. Having narrow code lets me use more of that screen real estate

                                                    1. 1

                                                      … you realise if it’s narrower it’s just going to be longer right? You aren’t “saving” any space - you’re just moving it down.

                                                      1. 3

                                                        At the point where that actually is a difference, take your 1000 wide lines.

                                                        1. 2

                                                          right, because of course the response to obvious logic is hyperbole.

                                                          1. 2

                                                            No, because it’s rare that I’ve seen code get substantially longer when made thin.

                                                        2. 2

                                                          If most lines are short, then there’s a great deal of empty space on the right. Or do you impose a minimum length as well?

                                                          I could maximize my editor and unwrap all lines, and only about 4% of the right half of the screen will be used at all. Two less lines on the left and 50 more lines on the right is a serious savings.

                                                        3. 0

                                                          Having narrow code lets me use more of that screen real estate

                                                          editors can wrap lines!

                                                          1. 2

                                                            And when it does you have to logically follow the new flow of code from line to line without actually breaking lines.

                                                    2. 1

                                                      Some say that it is because the IBM punch card was 80 characters per line:

                                                      https://en.wikipedia.org/wiki/Punched_card#IBM_80-column_punched_card_format_and_character_codes

                                                    3. 0

                                                      I vehemently disagree with this. Once one acknowledges the presence of arbitrary and ritualistic practices in computing, one starts to notice them everywhere. This eighty column ’‘standard’’ is one such tribal fire people will dance around.

                                                      This article makes no note whatsoever of viewing multiple files stacked vertically rather than side-by-side horizontally. My Emacs on a portrait-oriented 1080p monitor can display over one hundred columns just fine and I can easily view multiple files stacked vertically if I need to. On a landscape-oriented screen, I’m never really inconvenienced by horizontal viewing, anyway.

                                                      What incenses me about the eighty column convention is how arbitrary it is. What I do is use one hundred columns, as that’s a nice base-ten number, and for some purposes, such as Lisp programming, I’ll use one hundred and fifty columns. I don’t use two hundred columns because that doesn’t fit well on any of my screens and I’ve also never had a need for that.

                                                      In any case, one hundred columns is where I set my fill-column when composing email, normal text documents, and other such things. I’m also not going to sit happy with ragged right normal text, such as in documentation, when I can easily justify it and then permit it to be nicely read by others.

                                                      In closing, my point is you should always be looking to these ’‘standards’’ and other nonsense and mulling over whether you agree with them or not. If you don’t, I strongly encourage any of you to choose your own way, rather than following ’‘the ways things have always been done’’. Anything else is intellectual death and computing as a field already has too many idiots who see fit to encourage their own opinions and then hide behind a crowd that agrees, burning heretics whenever they catch them.

                                                      Next, consider character sets and other ’‘natural ways to do things’’. You may be surprised by something you come up with and may then even find it superior.

                                                      1. 2

                                                        and for some purposes

                                                        The number one takeaway I would love to see spread wider is that different kinds of code need different rules.

                                                        For HTML, I have extremely short lines - no more than three syntactic elements to a line. Having to scroll up/down to find other parts of the code isn’t a problem in HTML, since related DOM has to be written together. This approach (eg each attribute on its own line) makes diffs very easy to read.

                                                        When working with mutable state, vertical scrolling costs much more attention, so fitting more onto the screen at once becomes more important.

                                                      2. 0

                                                        I can see 80 characters for code but trying to use this for data structure literals is a headache and a pointless one at that.

                                                        1. [Comment removed by author]

                                                          1. 6

                                                            It’s far from obvious that this research on reading news in proportional fonts applies in the same way to programming with fixed width fonts.

                                                            1. [Comment removed by author]

                                                              1. 2

                                                                I like 80 columns as a useful and nice rule of thumb, though I try to keep my lines shorter than that—under 50 is really nice. I don’t make any claims about this being better in any empirically verified sense. It’s basically just my aesthetic preference. It’s also quite an established tradition, and I like to stick to traditions sometimes.

                                                            2. 3

                                                              We’re talking about code here, not prose.

                                                              1. 1

                                                                I have tried to find good research on this before, and as far as I know it doesn’t exist.

                                                                While this study is interesting, it also has several problems:

                                                                • The number of participants is small (20) and not diverse (college students with good vision: “20/40 or better unaided or corrected vision”).
                                                                • As the introduction explains, there is conflicting other research.
                                                                • The effects on reading speed are fairly small, and it’s interesting that the preferences seem strongly split: “60% of participants chose either 35 cpl(30%) or 95 cpl (30%) as the most preferred line length. On the other hand, 100% of participants chose either 35 cpl (45%) or 95 cpl (55%) as the least preferred line length”, suggesting that personal preference may be a strong factor.
                                                                • There are other factors, mainly font size and line height, that interact with line length.
                                                                • This study is from 2005; computer screen, fonts, and website designs have changed since then.
                                                                • As was previously pointed out, it’s unclear how applicable this is to programming.

                                                                As mentioned, it’s an interesting study, and would love to see further research in to this for replication/verification. But citing it in this discussion with the claim that “research shows that [..]” seems like a classic example of “here’s a small-scale study that agrees with my position, ergo research agrees with my position!”