I understand the importance of succinct, clear code and that code line wrapping should be avoided, if possible. However, the requirement for this project is that no line should go beyond column 80 and I'm being asked to use verbose variable naming. Therefore, something as simple as a for loop parenthetical will need to be wrapped and that's where I'm finding Eclipse falling short.
It doesn't appear that Eclipse is capable of wrapping the parenthetical of a for loop or preserving the wrapping set. For example, my initialization statement, expression and update/counter are on separate lines like so:
for (initialization;
expression;
update/counter;)
{
//code...
}
When pressing Ctrl+Shift+f, Eclipse makes it:
for (initialization; expression; update/counter;)
{
//code...
}
Is there a way to get Eclipse to preserve this formatting. I've created a custom Eclipse formatter, but can't find any setting that will wrap the for loop parenthetical. I did see one post that suggested using //, but that won't work inside of a for loop's parenthesis.
I do not remember of an option to preserve the line feeds after each of the for's "initialization", "expression", "update". The rest can be done, but not the wrapping inside the for loop's parenthesis.
If you really need to preserve such a wrapping, you may want to disable the formatter altogether on these lines? If you go to the formater settings (Window > preferences > java > code style > formatter, then click "edit..."), then on the "Off/On Tags" tab (appeared in Eclipse 3.6 IIRC), you can enable tags to disable the formatter on specific parts of the code.
With the default tags, that would give something like :
// #formatter:off
for (initialization;
expression;
update/counter)
// #formatter:on
{
//code...
}
You can also use this way:
for (/**/initialization;
/**/expression;
/**/update/counter;)
/**/{
//code...
}
This also works:
for (initialization; //
expression; //
update/counter) {
// code...
}
Related
When I am writing anonymous classes, I want my anonymous class to look like:
SaleTodayOnly sale = new SaleTodayOnly() // line 1
{ // line 2
some implementation
}
But when I hit enter after line 1, Eclipse will automatically position my cursor at | on line 2:
SaleTodayOnly sale = new SaleTodayOnly() // line 1
| // line 2
some implementation
And when I backspace my way to the front and write {, Eclipse will reposition this { to:
SaleTodayOnly sale = new SaleTodayOnly() // line 1
{ // line 2
some implementation
How can I set my own indentation preferences (for this specific scenario only)?
edit: I have my anonymous class set to next line. It's probably a wrapping issue.
edit2: I give up. I'll just use java conventions of { on the same line as the anonymous class declaration...
edit3: after hunting around the Preference window, toggling without much effect + seeing how Format produces the right output whereas the problem described still persists -- I'd agree that this is probably a bug and I will file a report when I have time.
Go into your preferences. (Window -> Preferences, probably; on mac it'll be under the leftmost menu option ('Eclipse')) - in the filter type 'formatter' to find the entry Java > Code Style > Formatter.
The behaviour you are witnessing is non-standard so you must already have a format defined; you picked this indent behavior, or somebody did who set this as default formatter.
edit this format. Alternatively, check if your project has a custom formatting rule in which case, this same answer applies, but instead go via your project's properties and update the formatting rules there.
The specific rule you are looking for is Brace positions, Anonymous class declaration. You have this set to Next line indented. Set it to something else. It sounds like you want Next line (not indented).
I have been setting up the eclipse formatter and quite close to our desired outcome except for the following. I'm trying to ignore line wrapping for the conditions within the if statement
For example
My desired outcome is
if (callback.getType().equals("NameCallback")) {
callback.getInput()
.get(0)
.setValue(testUser.getUsername());
}
but instead I'm getting
if (callback.getType()
.equals("NameCallback")) {
callback.getInput()
.get(0)
.setValue(testUser.getUsername());
}
In the formatter I have set Line wrapping -> Function Calls -> Qualified Innovations to a line wrapping policy of 'Wrap all elements, except first element if not necessary' and force split. This works fine but our preference is to not have this rule invoked for if statement conditions or inside of () if easier. I know I can setup the On/Off tags for the formatter but hoping there is a way to get the same result without having to do this. Any ideas would be appreciated
Thanks
In order to customize the way you format an if else blocks, you need to jump to Control Statements :
How can I set a breakpoint in a single line lambda?
e.g. I'd like the (eclipse) debugger to halt, when outer.doSth(event) is called:
observable.addCallback(event-> outer.doSth(event));
You can't.
If you refactor it like this:
observable.addCallback(event-> {
return outer.doSth(event);
});
you can.
Well this answer is not for eclipse, but in intellij you can (15.x)
You have an option to set a break point either at the line (which is the first option in the image), or at the first lambda or at second one. And so on.
In Eclipse 4.14.0 when I set a breakpoint into a lambda it works automatically correct and I am able to debug the lambda expression. But be aware that Eclipse also stops at the breakpoint at the "line" itself (that's before the stream operation is executed, since it's lazy):
And here you see that I am able to see the value of the group variable:
So you don't have to reformat your code.
Just making #Holger 's comment on this answer an answer:
It is enough to break line after ->
observable.addCallback(event->
outer.doSth(event) //line break works here!
);
I just refactored a small part of a large project grown over years to have some methods accept a Collection where previously a List was required. for this, I had to rewrite some code à la
for (int i=0; i < someList.size(); i++) {
SomeType element = someList.get(i);
someMethod(element);
// ... more code not using i
// or sometimes just: someMethod(/*other args */ someList.get(i));
}
to
for (SomeType element: someList) {
someMethod(element);
// ... more code not using i
}
Since there are probably many more occurrences of this pattern, I wonder whether there is a way to automatically convert the old-style loop to the enhanced one, or at least report the loops that can be converted? (pmd:AvoidArrayLoops - we are using Sonar for code analysis - does something similar for arrays, but with a few false positives)
I could even imagine a regular expression might help, but do not consider myself well-versed enough to handle the part of establishing that the loop variable is only used in a get method of the list whose size is checked in the termination expression.
If you are using Eclipse:
Menu Window > Preferences, Java > Code Style > Clean Up.
Edit the profile
Tab Code Style
Control statements > Convert for loops to enhanced
Save (probably creating a new profile) and close the preferences
Create a Java project with your sources
Context menu of the source folder, Source > Clean Up...
Eclipse is able to do this with its Clean Up feature.
Select the project you try to change. From the menu Source choose Clean Up... and the next to review the changes.
You will have to configure loop enhancing under code style.
I have to read java file by java code and to determine the greatest nested count of if statements in it.
for example:
if (someCondition)
{
if (someCondition)
{
// Expression
}
}
In this case program should display greatest nested if depth is 2.
Now the problem is that position of curly brace after if is uncertain.
for example it can be like :
Curly brace start and end comes in same line
if (someCondition){}
OR
Curly brace start in next line
if (someCondition)
{
}
OR
Conditions without curly brace
if (someCondition)
if (someCondition) // Single line without curly brace
Can anybody suggest what will be the best way to get the required nested count?
You'll need to parse the Abstract Syntax Tree (AST) of the Java source code. See Java library for code analysis. Once you have the AST, you can do a search to find the longest path of nested conditionals.
As the answer already said, you should rely on the AST rather than viewing code manually for this. The AST will never be wrong, your own reading abilities most often will.
I don't know a complete solution right now, but I suggest you spend some time looking at existing tools for computing software metrics. Nesting depth is a typical metric and there should be tools around.
If you can't find anything, you can at least fall back to writing something like an Eclipse plugin. In that case, you could simply load the Java file in the Eclipse editor, and Eclipse performs all the hard work for you and gives you the AST for free. Determining the nesting depth of a given AST is then rendered a simple task. Developing a prototype for that shouldn't take more than a few hours. And it's easy to extend it to cover your whole project and have it answer questions like "which java file in our project has the maximum nesting depth and what depth is that?". But then again.. someone else will surely point out an existing tool that already does this and much more.
I82Much's answer will certainly get you there, but feels a little like cheating.
Knowing little about your project, I would think that a simple stack mechanism with a max value record would do the trick push on { and pop on }. Once you have that basic model working, simply add the special case of control statements with one line bodies (this is valid for if, for, while ...). In those cases, you'll be looking for those keywords, followed by ( and a ). Once you've encountered that combination, if the scan encounters either another control statement or a semi-colon before it encounters a { then this is one of those special cases and you should push (using a special marker indicating to pop on ; rather than }).