Many people like to break their Java code over several lines. I think this is a bad thing. Here is why.
Focus on the Important Part
When reading code, the left most part of lines matters much more. In which method am I? In which block am I? What operation is executed? On which object is it executed? What variable is the result assigned to? It is very hard to understand what a class is doing without that information.
I am much less interested in the part on the far right. Usually these are the details. To understand what a class is doing, I don’t need to know what the forth parameter to a method call on line 52 is. I am only interested in that information when I am working on that exact method call.
If someone adds line breaks they move the less relevant part to the left side. Having all that minor information in the space I look at most is distracting.
In addition to that every line break added to a file reduces the number of lines shown on my screen by one. The moment, I have to scroll in order to see where a method or a block ends, readability suffers significantly.
Indentation
Code indentation is a great thing. It lets you capture the structure of a piece of code automatically without even actually paying attention to it. This is a sense that every engineer develops automatically after some time. This tool is so powerful that some languages leveraged it and incorporated into the syntax.
When adding extra line breaks to a line of code there are two possible approaches:
- Use the same indentation for the second line as well.
- Add additional indentation for the second line. (Typically 2 tabs)
None of these approaches is optimal. With the first approach the reader can confuse the second line with the start of a new statement.
The second approach solves that problem. However now we end up with additional indentation that is completely unrelated to the structure of the code. This confuses the abovementioned sense and makes the code harder to read.
Larger Screens
I can only think of one plausible reason to wrap lines so frequently. Back in the old days, more than a decade ago, screen size was very limited. So not everything fitted on screen and adding line breaks was intended to prevent horizontal scrolling. However these days’ large high-resolution screens are readily available at reasonable prices. On modern 27″ screens even long lines fit very comfortably. Yet people keep applying the same formatting.
Conclusion
- Vertical screen space is much more valuable than horizontal screen space
- Inserting line breaks makes code harder to read.
- Avoid line breaks.