Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I Define Exceptions to Eclipse cleanup rules?

Tags:

java

eclipse

Most often the cleanup rules (Preferences > Java > Code Style > Clean Up) in Eclipse work perfectly and create nice-looking code.

But sometimes, especially with comments and concatenated string snippets (like inline SQL queries), the cleanup just messes things up, and destroys my formatting.

Is there a way to say to Eclipse "Don't touch this block of text! I have formatted it just the way I like, and you would make it just less readable"?

like image 952
Henrik Paul Avatar asked Oct 06 '08 09:10

Henrik Paul


2 Answers

I assume you do not really mean ‘Clean Up’, but the ‘Format source code’ option hidden within. It is configured in Preferences > Java > Code Style > Formatter. And, indeed, there is an option called ‘On/Off Tags’. Sadly, it’s off by default. You would now write it like so:

// @formatter:off
StringBuilder sql = new StringBuilder()
    .append("SELECT whatever \n")
    .append("FROM some_table");
// @formatter:on

It may well be possible that the accepted answer was correct at the time of writing, however, this was introduced in Eclipse 3.5, if I’m not mistaken.

like image 165
Michael Piefel Avatar answered Oct 30 '22 21:10

Michael Piefel


I have experienced the same problem, and while I don't have a solution, I can tell you how I work around the problem.

Because of how formatting works, I deliberately avoid lines of code that are excessively long. In general, when I keep lines short, it makes better decisions as to how to format the code. This can even work with SQL statements, for example:

public static final String SELECT_SOMETHING = "SELECT"
        + "OBJECTID, THIS, THAT, THEOTHER, THING"
        + " FROM DBNAME.DBSCHEMA.TABLE_T"
        + " WHERE ID = ?";

This statement formats reasonably, because where possible items were split apart and concatenated together. When I don't do this, I get unpredictable results:

public static final String SELECT_SOMETHING = "SELECT OBJECTID, SOMETHING FROM DBNAME.DBSCHEMA.TABLE_T WHERE ID = ?";

For comments, I place them all on a single line when possible, and allow it to word wrap when it does the formatting.

Also, it is possible to change the style using the code formatter to make things work better for your coding style. You may want everyone on the team to use the same format, just to avoid conflicts. Because it is easier to compare changes with other developers, or prior versions using your source control tool, even if it makes parts of your code less readable, using the formatter has still been to my advantage.

Still, I understand your frustration when the formatter makes bad decisions!

like image 35
srclontz Avatar answered Oct 30 '22 21:10

srclontz