Cook Computing

Code Line Length

June 24, 2006 Written by Charles Cook

Coding Horror has a piece on Text Columns: How Long is Too Long? The post quotes some research results which probably aren't really all that applicable to code because its not ordinary text and might look a bit strange if right-justified. Still, its a topic worth thinking about. Is there an optimum max line length for code, maybe different for each programming language, or is it ok to keep typing to the width of the editor viewport or even beyond?

On the whole I tend to write code with line length no greater than 80 columns (I use guidelines in Visual Studio as I described here). Ok, the first paid coding I ever did was in COBOL, so that may have corrupted me for ever, but there are advantages to keeping line length in the order of 80 to 100 characters max width. You can have two editor windows side-by-side on single screen and see all the code in both windows. Similarly when using tools to view the diffs between two files. You're not lured into excessive levels on indentation and avoid the Arrow Anti Pattern. You can print code without using landscape orientation. You tend to write complex conditional statements over multiple lines which makes them easier to understand. And You can read code without having to move your head side-to-side as if you're watching a tennis match.

I find it a bit depressing when I see a developer working on a wide screen with Visual Studio maximised, the code editor window stretched across most of the screen, and typing in lines of code which take up all the available width. That suggests a lack of insight into what they are doing. The size of their screen is determining how their code looks, to the likely detriment of the code. Are lines of code 200+ characters wide all that readable? How comprehensible is code when you have 10 or more levels of indentation? Say they're on a 19in screen now. What happens when they move to 24in. Do they now automatically move up to 250 character lines? Do they now use more levels of indentation in nested conditional or loop statements without any conscious decision to do so?

But the thing that irritates me the most is when I revisit my own code which was neatly crafted to fit into 80 columns with minimal use of indentation and find that someone has made changes, adding a few lines of 150 to 200 characters long. Aargh!