Related
General JavaDoc questions here:
How do I know if they are working? I know the format and what they're supposed to be doing, but how do I know if they're doing their job? Should it print out after compiling and running?
Another question - how many JavaDoc comments do I need? My professor really wants us to examine our methods in these commentaries, and explain any variables. Does that mean put it inside the method? or before the method but inside the class? or before the class?
Thanks for any help!
I think you may be a tad bit confused as to what JavaDoc actually does.
JavaDoc does not directly impact your program in anyway. JavaDoc is a means of compiling information about your program. Say you get a program and want documentation of what it does in a nice handy format. Common compilers like eclipse have an option to compile an html file full of documentation, just like it shows on the Java API documentation. https://docs.oracle.com/javase/7/docs/api/
This is all JavaDoc for the most part, it is generated from comments.
My teachers always tell me in regards to comments, you are not commenting for someone who doesn't read code. You don't need comments like....
// Prints out hello world
System.out.println("hello world");
A programmer knows this functionality already. Programmers are more interested in parameter names and what functions actually do. Example
/**
* #param a Number we are dividing into
* #param b Number we are dividing by
* #return Our quotient
*/
public static float divide(int a, int b) {
return (a/b); }
Will generate a page like this
Emphasis on the /** at the top, two asterisks denote that below contains JavaDoc. Most IDE's like Eclipse will highlight JavaDoc.
As you can see the names of the parameters are just a and b, in certain cases it is difficult to label parameter names by what their function may be, so it can save time to use JavaDoc to give a description of them, instead of someone scrolling through your code trying to figure out what the hell they do. You are creating a guide for your program to modify and update it.
JavaDoc is literally a guide to how all your functions, classes, variables work in your program.
I am building a app like a compiler with my own script language. The user will enter the code and the output will be another app.
So I need tell to user if some line is wrong and why it is.
But I don't know how to start.
I thought this:
All lines will start with a keyword, except for those who start with an variable. So different that are wrong.
So, I can calculate the next valid entries and check them.
Also, I thought that I can check each line, but it's complex because I can have this
var varName { /* ... */ };
Or
var varName {
/* ... */
};
Or Even
var varName
{
/* ... */
};
So why not remove the break-lines and check? Because I will lose the line number, which in this case is the most important.
Maybe I'm going to create a map between the code with and without break-line.
But first I want to hear you, if you already has this experience or you have any idea.
Thanks
There are formal languages to describe syntax and semantics of the language and there are tools that will generate parsers out of these descriptions. I suggest reading on flex and bison for starters.
It'll be fairly complicated to write your own language. But totally doable.
To able to recognize if a line is wrong, in the syntactical sense, you'd need to build a parser.
The parser checks the context-free grammar for a correct derivation of a structure from its tokens.
First you need to tokenize the file, then reconstruct it into a parse tree (to check syntax).
I took a class in this, CS 241. There's a very nice set of course notes which this is all explained in detail.
https://github.com/christhomson/lecture-notes/blob/master/cs241.pdf
You should check tools like: lex, bison and yacc.
lex is lexical analyser generator. It generates a code, which could be used for breaking the script to tokens (like numbers, keywords and so on...).
bison and yacc are both parser generators. Both can be used for generating code for parsing your language (combining tokens to statements).
Just google tutorials for those tools.
Is there any need for code with author's name added in every function or even the files?
Yes code will be in source control and many programmers involved
According to Code Complete, comments are used to illustrate the purpose of the code. Using it for other purposes may result in 'comment decay'.
That said, keeping track of code ownership, change-log and who last modify the file, IMHO, is the job of a source control repo like SVN and such, and should not be inside the comments. Unless it is a license of some sorts. Or use an IDE's bookmark system to keep track of who authored a function, and who is the person responsible for it.
All this are just my 2 cent worth, though.
If the code is under source control, no.
That kind of data should be stored in the source code repository.
If the code is meant to be widely distributed (in other environment without any kind of repository), then yes, that could be useful. (some java sources do include that kind of information, as well as the release number from which some evolution of the code are available)
Obviously that kind of information (for widely deployed code base) is at the file level only.
Consider for example the source code of java.lang.Boolean in Java:
/**
* [...]
* In addition, this class provides many methods for
* converting a {#code boolean} to a {#code String} and a
* {#code String} to a {#code boolean}, as well as other
* constants and methods useful when dealing with a
* {#code boolean}.
*
* #author Arthur van Hoff
* #version 1.60, 05/05/07
* #since JDK1.0
*/
public final class Boolean implements java.io.Serializable,
Comparable<Boolean> {
[...]
You do not have all the authors from the beginning of time, only the most recent one, with the associated last major version for the most recent modification, and the version for the original introduction of the class.
That can help for API tooling for example, when you want to maintain good APIs.
But informations about the author is still limited to the file, not the functions: he represents the coordinator or aggregation manager for all the functions present in the class, even though there may have been more than one contributor over time.
As such, this is a public information, worthy of being put explicitly in the file, as opposed to a private meta-data (who writes what), stored as all other meta-data (date, version, branch, merge information, ...) in a source code repository.
Yes code will be in source control
Then no. Source control takes care of tracking this (blame).
Especially for team OpenSource projects, it might be useful or necessary to indicate the author of a particular piece of code. But commenting on every single function seems really excessive, especially since most of a class will be written by the same author (n’est-ce pas?). I like the Java library convention of specifying the author(s) for each class. Somehow, this seems to be the right trade-off.
On the flipside, if you co-authored a class, you’re to blame if someone else writes bad code in it. I actually think that this is a good thing. A class (in OOP, at least) is one entity so the quality is determined by its overall quality. If one function is bad, so is the whole class.
In some projects, author names can be used to give due credit to someone who put more effort into development than expected of him. Such recognition can improve motivation.
No. You or the company you work for implicitly has copyright. But that being said for tracking purposes it can be useful to ask that person what this code did later.
yes it is needed. Also if possible give the date alongwith the name. It is used for the tracking purpose as well as gives priviledge to others to know the owner of that function.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm wondering if people have a standard format for comments in their code. Not things like xml comments for a method or class but rather comments within a method.
See also:
Is there a standard (like phpdoc or python’s docstring) for commenting C# code?
You should really consider a couple things to make good comments beyond formatting.
Do not simply restate what the code is doing. For example,
// Start the services
StartServices();
is a frigging terrible comment!
Describe why. Why is the code doing what it's doing? What's the business assumption or algorithm step?
Format your comments for maximum readability. Tab them properly, leave spaces where necessary, etc.
If someone has already started commenting in a standard way, don't break that standard.
Check this article on MSDN about writing effective comments: http://msdn.microsoft.com/en-us/library/aa164797.aspx
// I usually write comments like this
Where I work it is required to use standard xml comment style for most of the declarations (classes, methods, some properties) (we use C#).
Sometimes you can see header/footer comments in use.
/****************************************************/
// Filename: Customer.cpp
// Created: John Doe
// Change history:
// 18.12.2008 / John Doe
// 14.01.2009 / Sara Smith
/****************************************************/
/* Here goes a lot of stuff */
/****************************************************/
// EOF: Customer.cpp
/****************************************************/
Something like this was used at one of my old places of work. In my opinion too much of unnecessary stuff. Change history is nicely seen these days through a version control system.
In many good software shops there are internal guidelines as to when and how to write comments. Documents are typically referred to as "Source code style policy" or something. It is very important to adhere to one common style in commenting the code.
Of course this commenting hype shouldn't go too far as to comment every little piece of code, especially the obvious ones.
/// <summary>
/// Handles the standard PageLoad event
/// </summary>
/// <param name="sender">
/// Event sender
/// </param>
/// <param name="e">
/// Event arguments
/// </param>
public void Page_Load (object sender, EventArgs e)
{
// Do something here
}
This one is a good example of over-obsession with commenting. Something like this adds exactly zero information but only adds noise to the source file. And we have to do it at work as required.
My personal opinion is add comments when you have something to say or explain, not just for the sake of commenting everything.
/**
* block comments to document a method for javadoc go like this
* #param
* #return
* #exception BTKException
* #see BTK
*/
Comment on the line above the code (block) that does what you're describing
// This is a comment.
Some code goes here
Avoid doing stuff like
// ----------------
// IMPORTANT COMMENT
// ----------------
And I avoid using the
/* comment */
And perhaps most importantly, clean up comments! A comment that describes non-existent functionality is worse than no comment at all.
//For one line, I write them like this
/*
For multiple lines of text
I write them like this
*/
/*
for(multiple lines of code){
I.WriteComents(With("//"));
Reason==If(I.Remove('The top begin-quote mark') then
I.Worry.Not('About removing the close-quote mark');
//*/
The problem with comments within a method (rather than in an interface), is that they are actually not meant to be seen by anyone except for people maintaining that method. Therefore, there is no real need for a standard for the comments. They don't get published anywhere, they're not publicly visible, callers will generally never see them.
In general, comments inside code should follow four rules:
They should not state the obvious
They should be consistent with what they describe
It should be clear what they describe (e.g., which line, block).
They should be readable by any future maintainer.
That being said, there is often a tendency to place information that is important to the callers as an internal comment. For example: "OOPS, This doesn't handle negative numbers". Whenever you see an internal comment, reconsider whether the header documentation should be updated, or use a tool that "pushes" the comments to the awareness of function callers (I have a tool like that for Java).
/* I will sometimes write
comments like this */
I can't believe we missed the REM keyword.
Though to be fair, it's for REMARK not COMMENT.
# ----------------------------------
# BIG IMPORTANT COMMENTS IN PERL/SH
# ----------------------------------
Comments standards are most useful when the comment will be parsed by an external tool (usualy, a document generator, like javadoc).
In this case, the external tool will state the standards.
For other cases, see How do you like your comments? (Best Practices)
//Cheap Debugger
//Response.Write(MySQLStringBecauseINeedToKnowWhatsBroken);
' I usually write comments like this
<!--How about comments like this!?-->
There are packages that will help write and format documentation. They require some specific changes so they can identify classes of comments.
such as doxygen:
http://www.doxygen.nl/manual/docblocks.html
/*! \brief Brief description.
* Brief description continued.
*
* Detailed description starts here.
*/
(* Modula-2 comments go like this *)
If you are paranoid and don't use or trust source control, you might do this
// Initials-YYMMDD-fixNo-Start
dosomething();
// Initials-YYMMDD-fixNo-Finish
It makes a bloody big mess, but it gives you some way to rollback changes.
But I'd suggest using source control
There can be religious wars on this subject.
What I try to do, that doesn't cause too much warfare, is
// explain the purpose of the following statement in functional terms
... some statement ...
The idea is, if I run the code through a program that deletes everything except the comments, what is left is pretty good pseudocode.
Something that's useful as a way to comment out code that you think you might need again is:
/*
... some code ...
/**/
then modify the first line - either delete it, or change it to /**/
/**/
... some code ...
/**/
/*
* Brief summary of what's going on.
*/
int code_that_goes_on(int c)
{
/* and then if I have to remark on something inside... */
return 0;
}
99% of compilers will support // comments, which is awesome, but that 1% still exists, and it's not too difficult to make life livable for them.
EDIT: The Delphi comment is a bit obtuse, but does point out a real deficiency. I intend this to be a C-specific answer.
I don't think there is a standard for what you are asking. And I don't see how it would add any benefit from /// comments on the method itself.
For creating documentation from your C# classes take a look at Sandcastle.
In C/C++/C#/Java, when I have a comment explaining a block of code:
// comment
code;
more_code;
when a comment is explaining a single line:
code; // comment
I usually use // for single sentence comments and /* ... */ comments for multi-sentence comments.
One comment style in C++/Java etc is this:
// Use // for all normal comments...
// and use multiline comments to comment out blocks of code while debugging:
/*
for(int i = 0; i < n; ++i) {
// If we only use // style comments in here,
// no comment here will mess up the block comment.
}
*/
I think it is an interesting point, even if it's not that incredibly useful.
My code is self-documenting. I need no comments.
I'm surprised that not more people recommended doxygen. It is a good way of documenting code, with the side effect that it can automagically generate html + pdf API documentation at the end of the day.
I prefer commenting this way for function
/**
* Activates user if not already activated
* #param POST string verificationCode
* #param POST string key
* #return true on success, false on failure
* #author RN Kushwaha <rn.kuswaha#gmail.com>
* #since v1.0 <date: 10th June 2015>
*/
public function activateUserAccount() {
//some code here
}
I use single line comment for code descriptions like
//check if verificationCode exists in any row of user table
code here
You might want to at least consider using standard comment formats for the PHP Reflection Class: https://www.php.net/manual/en/reflectionclass.getdoccomment.php
My sites compress html so a comment like
// comment here
in JS will crash the java script.
The specs for using // in PHP is only supposed to be a "short comment" ie: one line. Personally I don't think they should be used for more than one line.
Using them also makes it impossible to compress - or a lot harder to compress than what it should be.
Lastly.
Human interpretation is NOT absolute - a computer code is :)
So if you have a code that needs to or should be read - (Go Nasty) and don't comment it. ie: Force the reader to read the code rather than you relying on their interpretation of your comment.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 months ago.
Improve this question
I have seen the other questions but I am still not satisfied with the way this subject is covered.
I would like to extract a distiled list of things to check on comments at a code inspection.
I am sure people will say things that will just cancel each other. But hey, maybe we can build a list for each camp. For those who don't comment at all the list will just be very short :)
I have one simple rule about commenting: Your code should tell the story of what you are doing; your comments should tell the story of why you are doing it.
This way, I make sure that whoever inherits my code will be able to understand the intent behind the code.
I comment public or protected functions with meta-comments, and usually hit the private functions if I remember.
I comment why any sufficiently complex code block exists (judgment call). The why is the important part.
I comment if I write code that I think is not optimal but I leave it in because I cannot figure out a smarter way or I know I will be refactoring later.
I comment to remind myself or others of missing functionality or upcoming requirements code not present in the code (TODO, etc).
I comment to explain complex business rules related to a class or chunk of code. I have been known to write several paragraphs to make sure the next guy/gal knows why I wrote a hundred line class.
If a comment is out of date (does not match the code), delete it or update it. Never leave an inaccurate comment in place.
Documentation is like sex; when it's
good, it's very, very good, and when
it's bad, it's better than nothing
Write readable code that is self-explanatory as much as possible. Add comments whenever you have to write code that is too complex to understand at a glance. Also add comments to describe the business purpose behind code that you write, to make it easier to maintain/refactor it in the future.
The comments you write can be revealing about the quality of your code. Countless times I've removed comments in my code to replace them with better, clearer code. For this I follow a couple of anti-commenting rules:
If your comment merely explains a line of code, you should either let that line of code speak for itself or split it up into simpler components.
If your comment explains a block of code within a function, you should probably be explaining a new function instead.
Those are really the same rule repeated for two different contexts.
The other, more normal rules I follow are:
When using a dynamically-typed language, document the expectations that important functions make about their arguments, as well as the expectations callers can make about the return values. Important functions are those that will ever have non-local callers.
When your logic is dictated by the behavior of another component, it's good to document what your understanding and expectations of that component are.
When implementing an RFC or other protocol specification, comment state machines / event handlers / etc with the section of the spec they correspond to. Make sure to list the version or date of the spec, in case it is revised later.
I usually comment a method before I write it. I'll write a line or two of comments for each step I need to take within the function, and then I write the code between the comments. When I'm done, the code is already commented.
The great part about that is that it's commented before I write the code, so there are not unreasonable assumptions about previous knowledge in the comments; I, myself, knew nothing about my code when I wrote them. This means that they tend to be easy to understand, as they should be.
There are no hard rules - hard rules lead to dogma and people generally follow dogma when they're not smart enough to think for themselves.
The guidelines I follow:
1/ Comments tell what is being done, code tells how it's being done - don't duplicate your effort.
2/ Comments should refer to blocks of code, not each line. That includes comments that explain whole files, whole functions or just a complicated snippet of code.
3/ If I think I'd come back in a year and not understand the code/comment combination then my comments aren't good enough yet.
A great rule for comments: if you're reading through code trying to figure something out, and a comment somewhere would have given you the answer, put it there when you know the answer.
Only spend that time investigating once.
Eventually you will know as you write the places that you need to leave guidance, and the places that are sufficiently obvious to stand alone. Until then, you'll spend time trawling through your code trying to figure out why you did something :)
I document every class, every function, every variable within a class. Simple DocBlocks are the way forward.
I'll generally write these docblocks more for automated API documentation than anything else...
For example, the first section of one of my PHP classes
/**
* Class to clean variables
*
* #package Majyk
* #author Martin Meredith <martin#sourceguru.net>
* #licence GPL (v2 or later)
* #copyright Copyright (c) 2008 Martin Meredith <martin#sourceguru.net>
* #version 0.1
*/
class Majyk_Filter
{
/**
* Class Constants for Cleaning Types
*/
const Integer = 1;
const PositiveInteger = 2;
const String = 3;
const NoHTML = 4;
const DBEscapeString = 5;
const NotNegativeInteger = 6;
/**
* Do the cleaning
*
* #param integer Type of Cleaning (as defined by constants)
* #param mixed Value to be cleaned
*
* #return mixed Cleaned Variable
*
*/
But then, I'll also sometimes document significant code (from my init.php
// Register the Auto-Loader
spl_autoload_register("majyk_autoload");
// Add an Exception Handler.
set_exception_handler(array('Majyk_ExceptionHandler', 'handle_exception'));
// Turn Errors into Exceptions
set_error_handler(array('Majyk_ExceptionHandler', 'error_to_exception'), E_ALL);
// Add the generic Auto-Loader to the auto-loader stack
spl_autoload_register("spl_autoload");
And, if it's not self explanatory why something does something in a certain way, I'll comment that
The only guaranteed place I leave comments: TODO sections. The best place to keep track of things that need reworking is right there in the code.
I create a comment block at the beginning of my code, listing the purpose of the program, the date it was created, any license/copyright info (like GPL), and the version history.
I often comment my imports if it's not obvious why they are being imported, especially if the overall program doesn't appear to need the imports.
I add a docstring to each class, method, or function, describing what the purpose of that block is and any additional information I think is necessary.
I usually have a demarcation line for sections that are related, e.g. widget creation, variables, etc. Since I use SPE for my programming environment, it automatically highlights these sections, making navigation easier.
I add TODO comments as reminders while I'm coding. It's a good way to remind myself to refactor the code once it's verified to work correctly.
Finally, I comment individual lines that may need some clarification or otherwise need some metadata for myself in the future or other programmers.
Personally, I hate looking at code and trying to figure out what it's supposed to do. If someone could just write a simple sentence to explain it, life is easier. Self-documenting code is a misnomer, in my book.
I focus on the why. Because the what is often easy readable.
TODO's are also great, they save a lot of time.
And i document interfaces (for example file formats).
A really important thing to check for when you are checking header documentation (or whatever you call the block preceding the method declaration) is that directives and caveats are easy to spot.
Directives are any "do" or "don't do" instructions that affect the client: don't call from the UI thread, don't use in performance critical code, call X before Y, release return value after use, etc.
Caveats are anything that could be a nasty surprise: remaining action items, known assumptions and limitations, etc.
When you focus on a method that you are writing and inspecting, you'll see everything. When a programmer is using your method and thirty others in an hour, you can't count on a thorough read. I can send you research data on that if you're interested.
Pre-ambles only; state a class's Single Responsibility, any notes or comments, and change log. As for methods, if any method needs substantial commenting, it is time to refactor.
When you're writing comments, stop, reflect and ask yourself if you can change the code so that the comments aren't needed. Could you change some variable, class or method names to make things clearer? Would some asserts or other error checks codify your intentions or expectations? Could you split some long sections of code into clearly named methods or functions? Comments are often a reflection of our inability to write (a-hem, code) clearly. It's not always easy to write clearly with computer languages but take some time to try... because code never lies.
P.S. The fact that you use quotes around "hard rules" is telling. Rules that aren't enforced aren't "hard rules" and the only rules that are enforced are in code.
I add 1 comment to a block of code that summarizes what I am doing. This helps people who are looking for specific functionality or section of code.
I comment any complex algorithm, or process, that can't be figured out at first glance.
I sign my code.
In my opinion, TODO/TBD/FIXME etc. are ok to have in code which is currently being worked on, but when you see code which hasn't been touched in 5 years and is full of them, you realize that it's a pretty lousy way of making sure that things get fixed. In short, TODO notes in comments tend to stay there. Better to use a bugtracker if you have things which need to be fixed at some point.
Hudson (CI server) has a great plugin which scans for TODOs and notes how many there are in your code. You can even set thresholds causing the build to be classified as unstable if there are too many of them.
My favorite rule-of-thumb regarding comments is: if the code and the comments disagree, then both are likely incorrect
We wrote an article on comments (actually, I've done several) here:
http://agileinaflash.blogspot.com/2009/04/rules-for-commenting.html
It's really simple: Comments are written to tell you what the code cannot.
This results in a simple process:
- Write any comment you want at first.
- Improve the code so that the comment becomes redundant
- Delete the now-redundant comment.
- Only commit code that has no redundant comments
I'm writing a Medium article in which I will present this rule: when you commit changes to a repository, each comment must be one of these three types:
A license header at the top
A documentation comment (e.g., Javadoc), or
A TODO comment.
The last type should not be permanent. Either the thing gets done and the TODO comment is deleted, or we decide the task is not necessary and the TODO comment gets deleted.