I want that when i mouse over a method i would be able to see my documentation of what the method does like when i put the mouse over Java's method I know that /** */ is how its done but:
How do you explain what the Params Stands for?
How do you create a new line, or make a word bold or italic?
In most major IDEs, such as IntelliJ's IDEA, Apache Netbeans or Eclipse; you can type
/**
and press enter and it will generate the Javadoc for your method, including parameters, return values, etc. You just need to put in the descriptions.
The same applies for class declarations (the Javadoc comment always relates to the following element)
For instance
/**
* create_instance
* #param array of attributes for instance containing web, db, arrival_rate, response_time for instance
* respectively.
* #return Instance object
*/
How do you explain what the Params Stands for?
Use #param tag:
/**
* #param paramName Explanation of the param
*/
public void foo(String paramName);
How do you create a new line, or make a word bold or italic?
Use standard HTML, i.e. <p></p>, <br/>, <strong> and <em> (or less semantic <b> and <i>)
Related
TL;DR: How to preserve the Javadoc, line- and block-comment when creating a new java type based on a given type?
Long:
I am batch converting an infinite amount of types (Java classes) based on an unwanted base class towards Java enum types by using a headless eclipse application using JDT. My approach is to create a new EnumDeclaration based on the type information and adding the EnumConstantDeclarations based on the FieldDeclarations (exluding the serialVersionUID) of the initial class type. After that I add the MethodDeclarations (excluding the constructor) by simply adding a clone of the original MethodDeclarations to the BodyDelcaration of the newly created EnumDeclaration. Once I have done that, which is quite straight forward thanks to the great API, I do the following...
// create the EnumDeclaration from the given UnwantedClass CompilationUnit
final EnumDeclaration enumTypeDeclaration = createEnumDeclaration(cu, astRoot, methodDeclarations, ast);
// Find the original UnwantedClass TypeDeclaration and replace it with the new EnumDeclaration
astRoot.accept(new ASTVisitor() {
#Override
public boolean visit(final TypeDeclaration node) {
rewriter.replace(node, enumTypeDeclaration, null);
return false;
}
});
...to replace the original Java class Type with the new EnumDeclaration. This works almost perfectly. The only thing missing are all the Line-, Block- and JavadocComment elements of the original Java type. I found out that you can at least retrieve all Comment instances by:
List<Comment> comments = cu.getCommentList();
if (comments != null) {
for (Comment comment : comments) {
comment.accept(visitor);
}
}
That gives me all the comment, but I haven't figured out how to map a Comment instance to a BodyDeclaration, because these Comment instances are basically free floating all over the Source file and are only linked by their startPosition within the Source file.
There is the getAlternateRoot method, but I haven't managed either to utilize that one.
The question is: How do I preserve the Comment instances from the original type and put them at the correct position in the new type?
It seems, there is no straight forward approach to solve this, because javadoc (or just comments in general) in java files have no direct relation to the actual code they are meant to comment. Its just common sense among developers that we are usually put the comment above the code we are commenting. So I took the following path to solve this:
Create an starting position based index which maps an Integer (the starting position) to so called CommentEntry instances, which is basically a tuple consisting of the org.eclipse.jdt.core.dom.Comment and the actual text, which I extract by simply substring the source string of the compilation unit.
I visit my original CompilationUnit and retrieve all relevant ASTNode, which are Type-, Field- and MethodDeclaration instances in my case and map those on their starting positions.
Now I iterate over all mapped CommentEntry positions from 1. and associate them with an ASTNode instance, which is mapped to the same position (from the map of 2.). The result is then a map with ASTNode -> CommentEntry.
While building my new EnumDeclaration I query the map from 3. either by using the actual ASTNode type (TypeDeclaration only exists once), the actual instance of the ASTNode (I use attributes from the orignal FieldDeclarations to create the EnumConstants), or use the ASTMatcher to identify the correct MethodDeclaration, because I had to clone these in order to be able to "copy" them into the new EnumDeclaration Body section.
The adding of the comment isn't as straight forward as I thought, because in newer JSL you cant simply set the comment String in javadoc (only supported in JSL2, but in this version we hadn't enums). So, I used the following code:
private void setJavadoc(final BodyDeclaration bodyDeclaration, final CommentEntry commentEntry) {
final Javadoc javadoc = (Javadoc) ASTNode.copySubtree(ast, commentEntry.getComment());
final TagElement tagElement = ast.newTagElement();
final TextElement textElement = ast.newTextElement();
textElement.setText(commentEntry.getText());
tagElement.fragments().add(textElement);
javadoc.tags().add(tagElement);
bodyDeclaration.setJavadoc(javadoc);
}
As you can see, the actual comment text can be simply added by using a TextElement, even though it contains Tags. To make it perfect you may need to substring the comment text previously extracted from the source file, because it will contain the /** and */.
I'm teaching myself Java and was hoping for feedback regarding this question:
Write a Java interface with two methods, one that adds two doubles together returning the sum and one that multiplies two doubles together returning the product. Use JavaDoc comments.
Am I missing anything? Is it appropriate to include #return in the JavaDoc comment for the interface?
/**
* This is an interface for basic math.
*/
public interface Math {
/**
* This method will be used to add two doubles.
* #param a a value to be added
* #param b the other value to be added
* #return the sum of the two doubles
*/
public double add(double a, double b);
/**
* This method will be used to multiply two doubles.
* #param a a value
* #param b the other value
* #return the product of the two doubles
*/
public double multiply(double a, double b);
}
Am I missing anything?
There is nothing fundamentally wrong or "missing" from the javadocs in their current form.
Is it appropriate to include #return in the JavaDoc comment for the interface?
It is absolutely appropriate. An interface is a form of API, and meaning of the value returned by an API method is a fundamental aspect of the interface. If the meaning of a method return value is not specified in an interface then a caller of the interface method can't know what to expect. This makes programming to the interface difficult.
Yes, it is appropriate to have #return.
Few things you can improve:
To follow Java coding conventions, start method names with lowercase
(e.g. use add instead of Add).
Have better parameter names. E.g.
use number1, number2 instead of a, b.
Start #param and #return descriptions with uppercase letters (e.g. #param number1 First number).
I thinks it is better to say Returns the addition of two given numbers than This method will be used to add two doubles.
I am new to programming/Java and have been trying to teach myself it the last couple of weeks using some free textbooks and online resources. I thought a good way to learn would be to build a role-laying game I enjoy into a Java program. That being said, I know lots of people don't document their code effectively and want to avoid this being a habit, so I am trying to document everything in as much detail as possible. I cannot figure out if I am documenting this correctly though, even when referencing the Javadoc page, so any help would be appreciated. Basically I have a class 'Character' which implements all the required aspects of a character in this game. As an examplle, I have an enum which is a list of possible ability scores for a character in the game:
/**
* AbilityScores is an enum type containing all the possible ability scores in the game. It is
* utilized by the HashMap {#link #abilities} for the keys with an int being used as the values.
*/
private enum AbilityScores {
STRENGTH,
DEXTERITY,
CONSTITUTION,
INTELLIGENCE,
WISDOM,
CHARISMA,
INSPIRATION,
ARMOURCLASS
}
Then I have the corresponding HashMap:
/**
* abilities is a {#link HashMap} collection that contains {#link AbilityScores} as
* keys and {#link Integer} as values.
*/
private HashMap<AbilityScores, Integer> abilities = new HashMap<AbilityScores, Integer>();
And then here is an example of my accessor method for a character's strength:
/**
* This method returns a character's strength in the form of an integer.
* #return strength as an integer.
*/
public int getStrength() {
return abilities.get(AbilityScores.STRENGTH);
}
Am I documenting this correctly or have I incorrectly used '#link' etc. I did find some examples but I wasn't 100% sure as I couldn't find an example (apologies if there is one) where it showed an entire one start to finish like this one.
Any input or guidance is appreciated!
Thank you
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
The continuation of the question.
I need to statically and publicly storage data as arrays but I don't want somebody to modify my data. I need only ability to read from those arrays. Therefore I think I should use something like constant arrays which are presented in C++.
As far as I understand Collections.unmodifiableList(Arrays.asList(...)) prevents from modify the list at run-time but not at compile-time.
I've made the following class (code is updated). I suppose I'm not reinventing the wheel because I cannot have the same result using unmodifiableList.
/**
* Emulates constant arrays from C++.
*
* #param <E> Type of elements. Has to be immutable type.
*/
public final class ConstArray<E> {
/** Stores elements. */
private final E[] storage;
/**
* Constructs the object.
*
* #param storage Elements.
*/
public ConstArray(final E[] storage) {
this.storage = storage.clone();
}
/**
* Returns element at {#code idx}.
*
* #param idx Index of returning element.
* #return Element at {#code idx}.
*/
public final E get(final int idx) {
return storage[idx];
}
}
The size method and some other methods are omitted.
I've tested the class and it works.
To paraphrase, if I provide my library and somebody try to modify my data, I think it's better when he/she will know immediately that it's not possible (my class doesn't have a method to modify anything) and if I used unmodifiableList he/she will notice only a crash of the program.
What are advantages and disadvantages of this class? Is there a way to improve this class?
UPD:
I decided to use #Hoopje 's advice (see answers). It's based on experience that I don't have: I'm only a Java beginner.
If "reinventing the wheel" is not disadvantage enough, I see one major disadvantage to your approach:
Arrays.asList and Collections.ummodifiableList return List instances, so they are integrated in the Java Collections framework. This means that you can easily use them in enhanced for loops (for (E item : list) { }), as streams (list.stream()), use all List methods, pass them to methods which expect Collection or List subclasses, etc.
A minor point is that your class makes a copy of the array, whereas both Arrays.asList and Collections.ummodifiableList return views of their argument, so they do not copy the array.
By the way, creating a shallow copy of an array does not require "magic": you can do
this.storage = storage.clone();
Answer to UPD1:
Yes, it is unfortunate that Java does not provide interfaces for collections which cannot be modified. Thus, immutable List instances will have, for example, an add(E) method which simply throws an exception. So there is no compile-time guarantee for immutability.
However, in the Javadoc for your method you will of course write that the returned list is immutable. And if the user of your library tests his/her software, he will very deterministically see the exception and realize that he/she made a programming error.
And believe me, the users of your library will very much hate you if you take away their possibility to use the returned list in Collection-based APIs, just for the small advantage of not having any methods that look as if they would modify it.
My understanding is that once a document is loaded into Jsoup, using Jsoup.parse(), no parsing is required again as a neatly hierarchical tree is ready for programmer's use.
But what I am not sure whether top-level select() is more costly than inner-level select().
For example, if we have a <p> buried inside many nested <div>s, and that <p>'s parent is already available in the program, will there be any performance difference between:
document.select("p.pclass")
and
pImediateParent.select("p.pclass")
?
How does that work in Jsoup?
UPDATE: Based on the answer below, I understand that both document.select() and pImediateParent.select() use the same exact static method, just with a different root as the second parameter:
public Elements select(String query) {
return Selector.select(query, this);
}
Which translates into:
/**
* Find elements matching selector.
*
* #param query CSS selector
* #param root root element to descend into
* #return matching elements, empty if not
*/
public static Elements select(String query, Element root) {
return new Selector(query, root).select();
}
I am not surprised, but the question now is how does that query work? Does it iterate to find the queried element? Is it a random access (as in hash table) query?
Yes, it will be faster if you use the intermediate parent. If you check the Jsoup source code, you'll see that Element#select() actually delegates to the Selector#select() method with the Element itself as 2nd argument. Now, the javadoc of that method says:
select
public static Elements select(String query, Element root)
Find elements matching selector.
Parameters:
query - CSS selector
root - root element to descend into
Returns:
matching elements, empty if not
Note the description of the root parameter. So yes, it definitely makes difference. Not shocking, but there is some difference.