I have a requirement, I want to put in-line/in-code comment to describe a line of code.
e.g Using single liner comment
private foo(List myNameList){
for(String name : myNameList){
//This prints each element of list
System.out.println(name);
}
}
But many GREEN comments all over the code don't looks pretty.
I am just looking for an annotation or a solution to replace each comment with annotation
e.g
private foo(List myNameList){
for(String name : myNameList){
#Comment(n)
System.out.println(name);
}
}
And just hovering over this #Comment should display my comment.
Note: In Comment(n) , n is an index of my messages/comments in some text file.
Don't use either.
If you think you need to write a comment explaining what a piece of code does, don't write a comment at all. Refactor the code. Extract out small, well-named methods that break the logic down into understandable pieces.
Inline comments in code should be rare, and provide information that cannot be gleaned by reading the code: for example, why something happens.
See: What is self-documenting code and can it replace well documented code?
Assuming you're an Eclipse user (hence green comments) I think what you actually should do is to change syntax coloring instead of developing an annotation.
In Preferences go to Java -> Editor -> Syntax Coloring, unfold Comments in the box on the right and choose whatever color you want (I suggest gray) for each type of the comments.
Additionally in Java -> Editor -> Folding make sure to have Comments selected.
Alternatively you could just remove all the comments. But it won't do unless you write self explanatory code. Start from the useless one. Refactor where they explain hard to comprehend code.
Related
Problem Description:
The default indentation for single or multiline comments does not always work properly. The following issues are being faced.
The indentation for single line comments never worked if there wasn’t already
at-least a space or a tab in-front of them.
The indentation for single or multi-line comments never worked if they were part of the IHiddenRegion for which a decrease of indentation was set. The current understanding is that the formatter for the respective IHiddenRegion will increase the indentation for the comments contained in it and will then set an overall decrease of indentation for the upcoming strictly alternating IHiddenRegion(s) or IsemanticRegion(s).
Important Note:
Kindly direct us to an already existing eclipse Xtext ticket, if this is a known issue. Or any stackoverflow threads that explain why this is happening. And what could possible be coded wrong within the formatters based on IFormmatter2. Else please read further, would appreciate useful hints, solutions that could help us reach to a solution.
Further Explanation:
By "default indentation" its meant that:
The methods applyHiddenRegionFormatting, createCommentReplacer or any other related methods to manipulate comments are not overridden.
The terminal rules for SL_COMMENT and ML_COMMENT are left unchanged and are as under (taken from Terminals.xtext):
terminal ML_COMMENT : '/*' -> '*/';
terminal SL_COMMENT : '//' !('\n'|'\r')* ('\r'? '\n')?;
There are also no other known changes made to manipulate comments in any form.
The current usage/behaviour understanding of AbstractFormatter2 w.r.t. indentation is as follows, please correct if its incorrect.
Given an EObject the following ways to set an indentation collectively for text of contained IHiddenRegion(s) and ISemanticRegion(s) are available:
EObject.interior().indent[]
Interior.(ISemanticRegion_Start, ISemanticRegion_End).indent[], where ISemanticRegion_Start & ISemanticRegion_End were taken for the keywords '{' and '}' respectively contained within the EObject.
Document.set(IHiddenRegion_Start, IHiddenRegion_End).indent[], where IHiddenRegion_Start was the next hidden region of ISemanticRegion_Start (as explained above) and IHiddenRegion_End was the previous hidden region of ISemanticRegion_End (as explained above).
For '2' and '3' above the current understanding is that the indentation will be increased for all the strictly alternating IHiddenRegion(s) and ISemanticRegion(s) that will be in between two ISemanticRegions (in case of '2') or between two IHiddenRegions (in case of '3', the two start and end boundary IHiddenRegions will be included) respectively.
The indentation of the comments showed exactly the same behaviour when using any of the above approaches. Please also advise if there is always a need to override certain methods to handle formatting of comments correctly. Or the default implementations provided for handling comments are sufficient.
As an example, the behaviour of the the formatters from our projects and the one from domain model example (org.eclipse.xtext.example.domainmodel) for the indentation of comments was identical. Hence providing below an example DSL with comments from the domain model example so that its easy to relate to it.
Example domain model DSL with comments:
package p1 {
/*
* ml one
*/
// sl 11
// sl 12
package p2 {
}
// sl two
package p3 {
}
// sl three
/*
* ml two
*/
/*
* ml three
*/
package p4 {
}
// sl four
/*
* ml four
*/
/*
* ml five
*/
}
In the example above comment "sl 12" is an example of the incorrect indentation case (1). And comments "sl four" and "ml four" are examples of case (2). As explained in the very beginning. Comment "sl 11" is an example of the right indentation of a single line comment when there was at-least a space or a tab in-front of it. The indentation of multi line comments works correctly also when there is no space or tab in-front of them.
Additional Points:
It was also tested if it makes a difference to use grammar access for aquiring access to the required ISemanticRegions, i.e. EObject.regionFor.ruleCall() instead of Eobject.regionFor.keyword(), but the results were the same.
Also in the domain model example the formatter extends XbaseFormatter while the formatter in our projects extends AbstractFormatter2, but the results of both formatters is also identical w.r.t. comments. The resulting DSL(s) and comments contained in them are in English language.
Thanks in advance.
you may try this workaround
class DomainmodelFormatter extends XbaseFormatter {
override ITextReplacer createCommentReplacer(IComment comment) {
var EObject grammarElement=comment.getGrammarElement()
if (grammarElement instanceof AbstractRule) {
var String ruleName=((grammarElement as AbstractRule)).getName()
if (ruleName.startsWith("ML")) return new MultilineCommentReplacer(comment,Character.valueOf('*').charValue)
if (ruleName.startsWith("SL")) {
if (comment.getLineRegions().get(0).getIndentation().getLength() > 0)
return new SinglelineDocCommentReplacer(comment,"//")
else
return new SinglelineCommentReplacer(comment,"//") {
override configureWhitespace(WhitespaceReplacer leading, WhitespaceReplacer trailing) {
// do nothing
}
override createReplacements(ITextReplacerContext context) {
return context
}
}
}
}
var String elementName=new GrammarElementTitleSwitch().showQualified().showRule().doSwitch(grammarElement)
throw new IllegalStateException('''No «ITextReplacer.getSimpleName()» configured for «elementName»''')
}
}
Is there a way to dynamically change output in Java? For instance, in a terminal window if I have:
System.out.print("H")
and then I have:
System.out.print("I")
The output will be:
HI
Is there a way to assign a position to outputs that allows you to replace characters dynamically? For instance (and I know this would not output what I want, I merely want to demonstrate my thinking) this:
System.out.print("H")
Thread.sleep("1")
System.out.print("I")
And it would first print out
H
and then after a second, replace the H with an I?
I'm sure this sounds stupid, I am just interested in dynamically changing content without GUIs. Can someone point me in the direction for this technique? Thank you very much in advance.
You might want to take a look at
System.out.printf
Look at the example shown here: http://masterex.github.com/archive/2011/10/23/java-cli-progress-bar.html
edit:
printf displays formatted strings, which means you can adapt that format and change it for your needs.
for example you could do something like:
String[] planets = {"Mars", "Earth", "Jupiter"};
String format = "\r%s says Hello";
for(String planet : planets) {
System.out.printf(format, planet);
try {
Thread.sleep(1000);
}catch(Exception e) {
//... oh dear
}
}
Using the formatted string syntax found here: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
As the comment says this solution is only limited to a singular line however dependent on your needs this might be enough.
If you require a solution for the whole screen then a possible solution would be (although quite dirty) would be to hook the operating system using JNA and get a handle on the console window, find its height and then loop println() to "clear" the window then redraw your output.
If you would like to read more then I can answer more questions or here is a link: https://github.com/twall/jna
You can use \b to backspace and erase the previous character.
$ cat T.java
import java.lang.Thread;
public class T {
public static void main(String... args) throws Exception {
System.out.print("H");
System.out.flush();
Thread.sleep(1000);
System.out.print("\bI\n");
System.out.flush();
}
}
$ javac T.java && java T
I
It will output H, then replace it with I after one second.
Sadly, it doesn't work in Eclipse console, but in normal console it does.
This is what you need (uses carriage return '\r' to overwrite the previous output):
System.out.print("H");
Thread.sleep(1000);
System.out.print("\rI");
The C library that is usually used to do this sort of thing is called curses. (Also used from scripting languages that rely on bindings to C libraries, like Python.) You can use a Java binding to it, like JCurses. Google also tells me a pure-Java equivalent is available, called lanterna.
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...
}
I'm tying to figure out how I can customize the Eclipse code formatter to break lines more to my liking. I'm trying to set the style for parameter lists, either in method declarations or calls. Looking for a mix of Wrap where necessary and Wrap all elements, every element on a new line. I want to Wrap where necessary, every element on a new line, which doesn't seem to exist. My logic is that no break is necessary for short lines, my eye can scan the parameter list horizontally:
public void myMethod(int p1, int p2, int p3) {
But for lists that do need to be broken, I would like every element on a new line, so I can scan vertically:
public void myMethodWithALotOfParams(
ReallyLongClassName param1,
AnotherLongName aLongParamName,
int p3) {
I can't seem to make this happen. I can wrap everything, including short lists. I can wrap only long lines, and continue stacking parameters on each line until I reach the margin. I can't trigger wrapping on long lines, then put each parameter on its own line.
This style can be seen in several places in Code Complete (2nd Ed).
UPDATE >>
I don't think there is anything built in to Eclipse to handle this, but I'm not afraid to write code. :) Eclipse is open source, so I tried to find the code that handles formatting, in hopes of building in the preferred behavior. Didn't have much luck on the first try, lots of abstraction, not much parsing and formatting. Hints?
look at this link
Window -> Preferences -> Java -> Code Style -> Formatter -> New (Profile) -> Edit -> Line Wrapping -> Never join already wrapped lines
Or change other parameters if you want to change line wrapping parameters.
I would like to have such a feature too, unfortunatly (as you already guessed) it's not possible, yet. If you like you can file a bug at the eclipse-bugzilla, here you will find some bugs about formatting in jdt: https://bugs.eclipse.org/bugs/buglist.cgi?quicksearch=jdt+formatter. Let us know if you file a new bug, so everyone interested can vote for it!
I was just wandering why is the prefix XXX ?
As far as I know its used for notes/reminders (or at least this is what I use it for and that is what the people on most of the links I googled use it for).
So does anyone know where the XXX prefix come from ?
From Sun/Oracle's Java code conventions, section 10.5.4:
Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken.
From the Hacker's Dictionary entry for "XXX":
A marker that attention is needed.
Commonly used in program comments to
indicate areas that are kluged up or
need to be. Some hackers liken `XXX'
to the notional heavy-porn movie
rating. Compare FIXME.
XXX, along with FIXME and TODO, is known in Eclipse as a task tag, and is indexed by the IDE to let you find the spots marked with those tags easily. You can edit such tags in the Eclipse Preferences -> Java -> Compiler -> Task Tags.
As to where it comes from: it probably emerged form the "tags" that programmers spontaneously wrote in their code to quickly mark a given line. While FIXME and TODO are explicit enough, the reason XXX was used could be a combination of these reasons:
The string "XXX" does not usually occur in regular source code and is easy to look for with tools such as grep or a simple text search in an editor;
Traditionally, "X marks the spot" which needs attention; triple X even more so;
The X key is very close to the Command/Alt/Windows keys and is easy to reach, being on the lower row of the keyboard.
I can't think of anything else...
Various reasons:
It's easy to search for.
No collision, as no sane person would use it as a variable.
It can used to mark code that needs e*X*tra special attention, dangerous code, not to be seen by underaged, etc.
I've worked with a team where XXX was used to point out a "bug or task that was not yet entered in Trac.". After it was entered in Trac the comment would be changed to TODO with the ID appended.
To Eclipse though, it's just a marker like TODO and FIXME. I imagine that it's originally used as a strong form of TODO. You usually see comments like this:
// TODO: Need to optimize this once n becomes greater than 1000.
But sometimes you'll have a comment like:
// TODO: Fix SQL injection bug before production release!
Unfortunately a quick grep wont make that SQL injection bug stand out among the 1000s of other TODOs. Using XXX here would help mark things that must be done before a milestone/release etc.
There's also a reference to it on Wikipedia:
XXX to warn other programmers of problematic or misguiding code.
It bugs me too, because XXX may also be used for masking input or format numbers,
Thus creating multi markers warning when you describe amount format:
/**
* #param amount (XXX or XXX.XX)
*/
public doSomething(String amount) {
Multiple markers at this line
-XXX or
-XXX.XX)
As #Jean-PhilippePellet suggested, you can remove it from
Preferences -> Java -> Compiler -> Task Tags