Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code line wrapping - how to handle long lines

I'm facing a particular line that is 153 characters long. Now, I tend to break things after 120 characters (of course, this is heavily dependent on where I am and the local conventions.) But to be honest, everywhere I break the line just makes it look bad. So I'm looking for some ideas on what I should do for it.

Here's the line:

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper = new HashMap<Class<? extends Persistent>, PersistentHelper>(); 

I'm open to both ideas about how/where to break the line (and why), as well as ways to shorten the line itself.

We're not a Java shop, and there aren't local conventions for this sort of thing, or obviously I would simply follow them.

Thanks!

like image 445
corsiKa Avatar asked Sep 16 '10 19:09

corsiKa


People also ask

How do you wrap a long line in VS Code?

You can toggle word wrap for the VS Code session with Alt + Z (macOS: Option (or Alt) ⌥ + Z ) or select View > Word Wrap from Menu.

How do you break a long line of code?

This is useful for code readability. To break an expression into multiple lines, wrap the expression around a set of parenthesis and break it down as you want. If the expression is already in a set of parenthesis, square brackets, or curly braces, you can split it to multiple lines.

Why do we need to break long lines of codes?

In addition to negatively affecting readability, having very long lines can destroy the positive impact of code indentation, which makes the code even harder to understand and maintain (because of chaotic line returns).


2 Answers

In general, I break lines before operators, and indent the subsequent lines:

Map<long parameterization> longMap     = new HashMap<ditto>();  String longString = "some long text"                   + " some more long text"; 

To me, the leading operator clearly conveys that "this line was continued from something else, it doesn't stand on its own." Other people, of course, have different preferences.

like image 129
Anon Avatar answered Sep 21 '22 17:09

Anon


This is how I do it, and Google does it my way.

  • Break before the symbol for non-assignment operators.
  • Break after the symbol for = and for ,.

In your case, since you're using 120 characters, you can break it after the assignment operator resulting in

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =         new HashMap<Class<? extends Persistent>, PersistentHelper>(); 

In Java, and for this particular case, I would give two tabs (or eight spaces) after the break, depending on whether tabs or spaces are used for indentation.

This is of course a personal preference and if your project has its own convention for line-wrapping then that is what you should follow whether you like it or not.

like image 26
Daniel Avatar answered Sep 20 '22 17:09

Daniel