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.
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 work on legacy systems and I used to see revision history of files or functions being modified every release in the source code, for example:
//
// Rev. No Date Author Description
// -------------------------------------------------------
// 1.0 2009/12/01 johnc <Some description>
// 1.1 2009/12/24 daveb <Some description>
// -------------------------------------------------------
void Logger::initialize()
{
// a = b; // Old code, just commented and not deleted
a = b + c; // New code
}
I'm just wondering if this way of documenting history is still being practiced by many today? If yes, how do you apply modifications on the source code - do you comment it or delete it completely?
If not, what's the best way to document these revisions? If you use version control systems, does it follow that your source files contain pure source codes, except for comments when necessary (no revision history for each function, etc.)?
Just rely on your version control system. Yes, just pure source code. If code is commented out I delete it. If I'm not sure I leave it there with a TODO comment.
I don't insert comments to reference tickets in the source but in the commit message. You don't need to document in the code what it used to look like.
Manual revision histories are hard to maintain, hence almost always out-of-date.
I trust the revision control system to give me this information. In addition to be correct, it can be much more precise, for example with pre-line annotations (who has changed that line last).
I do insert comments to reference tickets in the bug tracking system directly in the source when I feel that it is necessary, even though this info is also available in the commit message.
It does make sense to have a changes/release notes file per project (not per source file) that is manually maintained and updated for every release.
I used to work for a company that mandated this type of comment on all SPs that went to the database. I found it incredibly tedious and completely redundant over the notes we were required to enter into our source control system.
The main use of the inline comments was to validate that the deployment to a new environment was successful (like production). This also was a tedious process and was only used because there was no other method.
I have never found a use for inline comments like this anywhere else and found they only caused tedious headache inducing work.
I would advocate for a system where source control manages the comments and revision history and not the code. That is one of the purposes of the system and that's the best place for it. IMO.
Nowadays the best way to document these revisions is to let your version control do it, but that also means that you have to enforce the rule that developers write meaningful commit comments, or at least some bug tracking numbers, so it would be easy to figure out what they committed what for.
I've never seen revision history in code comments. At most I've seen the Javadoc #version tags to document the version.
The oldest version control method is like this:
logo2007-1.png, logo2007-2.png
Version control should be the best solution.
see also: http://betterexplained.com/articles/a-visual-guide-to-version-control/
This doesn't have to be Java, but it's what I'm dealing with. Also, not so much concerned with the methods and details of those, I'm wondering about the overall class file.
What are some of the things I really need to have in my comments for a given class file? At my corporation, the only things I really can come up with:
Copyright/License
A description of what the class does
A last modified date?
Is there anything else which should be provided?
One logical thing I've heard is to keep authors out of the header because it's redundant with the information already being provided via source control.
Update:
JavaDoc can be assumed here, but I'm really more concerned about the details of what's good to include content-wise, whether it's definitive meta-data that can be mined, or the more loose, WHY etc...
One logical thing I've heard is to keep authors out of the header because it's redundant
with the information already being provided via source control.
also last modified date is redundant
I use a small set of documentation patterns:
always documenting about thread-safety
always documenting immutability
javadoc with examples
#Deprecation with WHY and HOW to replace the annotated element
keeping comments at minimum
No to the "last modified date" - that belongs in source control too.
The other two are fine. Basically concentrate on the useful text - what the class does, any caveats around thread safety, expected usage etc.
Implementation comments should usually be about why you're doing something non-obvious - and should therefore be rare. (For instance, it could be because some API behaves in an unusual way, or because there's a useful shortcut you can use but which isn't immediately obvious.)
For the sanity of yourself and future developers, you really ought to be writing Javadocs.
When you feel the need to write comments to explain what some code does, improve the readability of the code, so that comments are not needed. You can do that by renaming methods/fields/classes to have more meaningful names, and by splitting larger methods into smaller methods using the composed method pattern.
If even after all your efforts the code is not self-explanatory, for example the reason why some unobvious code had to be written is not clear from the code, then apologize by writing comments. (Sometimes you can document the reasons by writing a test which will fail, if somebody changes the unobvious-but-correct code to do the obvious-but-wrong thing. But having a comment in addition to that is also useful. I prefix such comments often with "// HACK:" or "// XXX:".)
An overall description of the purpose of the class, a description for each field and a contract for each method. Javadoc format works well.
If you assign ownership of components to particular developers or teams, owners should be recorded in the component source or VCS metadata.
Let me pose a bit of background information before asking my question:
I recently joined a new software development group that uses Rational tools for configuration management, including a source control and change management system.
In addition to these tools, the team has a standard practice of noting any code changes as a comment in the code, such as:
///<history>
[mt] 3/15/2009 Made abc changes to fix xyz
///</history>
Their official purpose for the commenting standard is that "the comments provide traceability from requirement to code modification".
I am preparing to pose an argument that this practice is unnecessary and redundant; that the team should get rid of this standard immediately.
To wit - the change management system is the place to build traceability from requirement to code modification, and source control can provide detailed history of changes by performing a Diff between versions. When source code is checked in, the corresponding change management ticket is noted. When a CM ticket is resolved, we note which source code files were modified. I believe this provides a sufficient cross-reference for the desired traceability.
I would like to know if anyone disagrees with my argument. Am I missing some benefit of commented source code history that change management and source control systems cannot provide?
For myself, I have always found such comments to be more trouble than they're worth: they can cause merge conflicts, can appear as 'false positives' when you're trying to isolate the diffs between two versions, and may reference code changes that have since been obsoleted by later changes.
It's often (not always, but often) possible to change version-control systems without losing metadata. If you were to move your code to a system that doesn't support this, it would not be hard to write a script to convert the change history into comments before the cutover.
A comment allows you to find all the changes and their reasons in the code right where they are relevant without having to dig into diffs and version control system intricacies. Furthermore, should you decide to change of version control system, the comments will stay.
I worked on a large project with similar practice that had changed of source control system twice. There wasn't a day when I wasn't glad to have these comments.
Is it redundant? Yes.
Is it unnecessary? No.
I've always thought that code should be, of course, under version control, and that the current source code (the one that you can open and read today) should be valid only in present tense.
It doesn't matter if a report could have up to 3 axis in the past and last month you updated it to support up to 6 axis. It doesn't matter if you expanded some function or fixed some bug, as long as the current version can be easily understood. When you fix a bug, just leave the fixed code.
There's an exception, though. If (and only if) the fixed code looks less intuitive to you than the previous, incorrect one; if you feel that someone might come tomorrow and, just by reading the code, be tempted to change it back to what "seems more correct", then it's good to add a comment: "This is done this way to avoid... blah blah blah." Also, if the problem behind is an infamous war story inside the team's culture, or if for some reason the bug report database contains very interesting information about this part of the code, I wouldn't find it incorrect to add "(see Bug Id 10005)" to the explaining comment.
The one that jumps to mind to me is vendor lockin. If you ever moved away from Rational, you'd need to make sure that the full change history was maintained during the migration - not just the version of the artifacts.
When you're in the code you need to know why it's structured like that, hence in code commenting. Tools that sit outside the code, good though they may be, require far too much of a context shift in your brain to be useful. As well as that, trying to reverse engineer the code intent from documentation and a diff is pretty damn hard, I'd much rather read a line of comment any day.
There was a phase in the code I work on, back in the 1994-96 time frame, where there was a tendency to insert change history comments at the top of the file. Those comments are now meaningless and useless, and one of the many standard cleanups I perform when editing files containing such comments is to remove them.
In contrast, there are also some comments with a bug number at the location where the change is made, typically explaining why the ridiculous code is as it is. These can be very helpful. The bug number gives you somewhere else to look for information, and fingers the culprit (or victim - it varies).
On the other hand, items like this one - genuine; cleaned up last week - make me grit my teeth.
if (ctab->tarray && ctab->tarray[i])
#ifndef NT
prt_theargs(*(ctab->tarray[i]));
#else
/* Correct the parameter type mismatch in the line above */
prt_theargs(ctab->tarray[i]);
#endif /* NT */
The NT team got the call correct; why they thought it was a platform-specific fix is beyond me. Of course, if the code had used prototypes instead of just parameterless declarations before now, then the Unix team would have had to fix the code too. The comment was a help - assuring me that the bug was genuine - but exasperating.
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.