Formatting Java in Eclipse
The style that the Eclipse auto-formatter imposes on my Java code is 99% excellent. However, whenever I set up a new workspace, that 1% of style I disagree with eats away at my soul. I document the few things that I do change here because it’s easier to set them anew then try to migrate and synchronize my preferences across workspaces.
Typing
I find the auto-closing of "
, (
, and {
to cause more grief than benefit. This isn’t so much a style issue as a human-computer interaction issue. I make a few changes in the Eclipse preferences under Java / Editor / Typing.
Under automatically close, I uncheck the following:
- “Strings”
- (Parentheses), [square], and
brackets - {Braces}
Style
One customizes the style by visiting Eclipse’s preferences and selecting Java / Code Style / Formatter. Click Edit and rename the profile in order to make changes. Once in the editor, I make changes to the following sections.
Indentation
A lot of developers indent with four spaces. I do a lot of teaching and projecting, and I want to keep as much code on the screen as possible. Since I don’t like breaking lines, I reduce the tab size with the following settings:
- Tab Policy: Spaces only
- Indentation size: 2
- Tab size: 2
Line Wrapping
I don’t trust Eclipse to perform any line wrapping on my behalf. I select all options and set the following:
- Line wrapping policy: Do not wrap
Comments
When I use Control-/
or Command-/
to comment out some lines of code and then reformat, I lose the indentation of the commented code. I prevent this with the following setting:
- Format lines comments on first column: Unchecked