I'm going through some new code I just wrote and adding NDoc sytle comments to my classes and methods. I'm hoping to generate a pretty good MSDN style document for reference.
In general, what are some good guidelines when writing comments for a class and for a method? What should the NDoc comments say? What should they not say?
I find myself looking at what the .NET framework comments say, but that gets old fast; if I could have some good rules to guide myself, I could finish my docs a lot faster.
In comments used to build API documentation, you should:
Explain what the method or property does, why it exists at all, and explain any domain concepts that are not self-evident to the average consumer of your code.
List all preconditions for your parameters (cannot be null, must be within a certain range, etc.)
List any postconditions that could influence how callers deal with return values.
List any exceptions the method may throw (and under what circumstances).
If similar methods exist, explain the differences between them.
Call attention to anything unexpected (such as modifying global state).
Enumerate any side-effects, if there are any.
If you end up with comments that don't add any value, they're just wasteful.
For example
/// <summary>
/// Gets manager approval for an action
/// </summary>
/// <param name="action">An action object to get approval for</param>
public void GetManagerApprovalFor(Action action)
...you added absolutely no value and just added more code to maintain.
Too often code is littered with these superfluous comments.
StyleCop provides hints for code and commenting style. The suggestions it gives are in line with the MSDN documentation style.
As for the contents of the comment, it should give the user of your code enough information on what kind of behavior to expect. It should also answer potential questions the user might have. So try to use your code as someone who doesn't know anything about the code, or even better, ask someone else to do so.
For properties, your comment should indicate whether the property is read only, write only or read write. If you look at all official MS documentation, property doc comments always start with "Gets ...", "Gets or sets..." and (very rarely, avoid write only properties usually) "Sets ..."
Don't forget what's a valid XML is. For example:
/// <Summary>
/// Triggers an event if number of users > 1000
/// </Summary>
(Error: invalid XML).
I write the <summary> comment to include the information I would want to know if I was the one calling that function (or instantiating that class).
I write the <remarks> comment to include information I would want to know if I was tasked with debugging or enhancing that function or class. Note: this doesn't replace the need for good inline comments. But sometimes a general overview of the inner workings of the function/class are very helpful.
As stated on the MSDN page, you use XML documentation comments to generate documentation automatically, so it makers sense if you're writing an API and don't want to work twice at both code and documentation, with the added benefit of keeping them in sync - every time you change the code, you modify the appropriate comments and regenerate the docs.
Compile with /doc and the compiler will search for all XML tags in the source code and create an XML documentation file, then use a tool such as Sandcastle to generate the full docs.
One thing about comments is UPDATING them. Too many people alter a function then don't change the comment to reflect the change.
Related
What is the use of XML comments in C# than signal line and multiple line comments.
i.Single line
Eg:
//This is a Single line comment
ii. Multiple line (/* */)
Eg:
/*This is a multiple line comment
We are in line 2
Last line of comment*/
iii. XML Comments (///).
Eg:
/// summary;
/// Set error message for multilingual language.
/// summary
From XML Documentation Comments (C# Programming Guide):
When you compile with the /doc option, the compiler will search for
all XML tags in the source code and create an XML documentation file.
Also XML comments used by Visual Studio for IntelliSense:
/// <summary>
/// This class performs an important function.
/// </summary>
public class MyClass{}
Will give you nice hints when you are typing code or hovering cursor over member which has xml comments:
NOTE: Usually you should add xml comments only to publicly visible types or members. If member is internal or private, then it's good, but not necessary. There is nice tool GhostDoc (available as extension to Visual Studio) which can generate XML comments from type or member name. It's nice to check if you have good naming - if generated comment is not clear, then you should improve name of member.
I also suggest use simple (non-xml) comments as little, as possible. Because comment is a form of code duplication - it duplicates information which you already have in your code. And here is two problems:
Your code is not clear enough and you should improve it (renaming, extracting classes or members) instead of adding comments
When code changes, comments often stay unchanged (programmers are lazy). So when time passes comments become obsolete and confusing.
Good comments should describe why you writing code instead of duplicating what code is doing.
XML comments, starting with ///, will get picked up by IntelliSense and it will get shown in a pop-up when looking at it from elsewhere. There is a MSDN page explaining how it works.
They will also be picked up by numerous tools that build documentation files, etc.
From MSDN:
When you compile with the /doc option, the compiler will search for
all XML tags in the source code and create an XML documentation file.
To create the final documentation based on the compiler-generated
file, you can create a custom tool or use a tool such as Sandcastle.
http://msdn.microsoft.com/en-us/library/b2s063f7.aspx
The XML comments are used to build API documentation which is readable by external tools. IntelliSense also reads these, and uses the contents to show the docs for your code in the assistance tooltips as you type (and in the Documentation window).
The compiler (optionally) extracts all those comments and puts them in a single standalone XML file next to your assembly; this can be parsed.
The idea was to have something like JavaDoc. Unfortunately Microsoft has failed to provide a mainstream mature tool to do so.
When you create a Dll assambly Xml comments provides the dll's user some information about function or something
Code in all languages usually allows for special comments. These comments can then be parsed by a process which creates automatic documentation of the code. Many libraries are documented this way.
In C# these tools are provided by Microsoft and you use the XML comments to declare that the comment should be picked up by the documentation process - if you have one set up. The comments are also picked up by auto complete.
See also doxygen, JavaDoc for implementations for other languages. See related question Good alternatives to Sandcastle to generate MSDN-style documentation
When asking around for the conventions of documentation comments in C# code, the answer always leads to using XML comments. Microsoft recommends this approach themselves aswell. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/xmldoc/recommended-tags-for-documentation-comments
/// <summary>
/// This is an XML comment.
/// </summary>
void Foo();
However, when inspecting Microsoft's code, such as ASP.NET Core, comments instead look like this.
//
// Summary:
// A builder for Microsoft.AspNetCore.Hosting.IWebHost.
public interface IWebHostBuilder
Does the included doc generation tool work with this convention, or is there a documentation generation tool that uses this convention instead of XML? Why does Microsoft use this convention in their code instead of the XML comments they recommend themselves?
Why does Microsoft use this convention in their code instead of the XML comments they recommend themselves?
C# documentation comments provide a precise syntax for encoding many types of content and references, such as to types, parameters, URLs, and other documentation files. It uses XML to accomplish this, and so inherits XML's verbosity. Remember that XML comments go way back to C# version 1, when it was a much more verbose language than it is today.
To avoid the readability problems with XML, Visual Studio displays the comments in a simplified, plain text format. You couldn't run this format back through a compiler. For example, if a comment has the term customerId, it may be ambiguous as to whether it refers to a method parameter or a class field. The ambiguity occurs infrequently enough to not be a problem for a human.
Ideally, there's be a single format that was well-defined for compiler input with good readability that avoids boilerplate. There is an issue open to modernize the comment syntax, but unfortunately, it hasn't gone anywhere in 3 years.
What is the use of XML comments in C# than signal line and multiple line comments.
i.Single line
Eg:
//This is a Single line comment
ii. Multiple line (/* */)
Eg:
/*This is a multiple line comment
We are in line 2
Last line of comment*/
iii. XML Comments (///).
Eg:
/// summary;
/// Set error message for multilingual language.
/// summary
From XML Documentation Comments (C# Programming Guide):
When you compile with the /doc option, the compiler will search for
all XML tags in the source code and create an XML documentation file.
Also XML comments used by Visual Studio for IntelliSense:
/// <summary>
/// This class performs an important function.
/// </summary>
public class MyClass{}
Will give you nice hints when you are typing code or hovering cursor over member which has xml comments:
NOTE: Usually you should add xml comments only to publicly visible types or members. If member is internal or private, then it's good, but not necessary. There is nice tool GhostDoc (available as extension to Visual Studio) which can generate XML comments from type or member name. It's nice to check if you have good naming - if generated comment is not clear, then you should improve name of member.
I also suggest use simple (non-xml) comments as little, as possible. Because comment is a form of code duplication - it duplicates information which you already have in your code. And here is two problems:
Your code is not clear enough and you should improve it (renaming, extracting classes or members) instead of adding comments
When code changes, comments often stay unchanged (programmers are lazy). So when time passes comments become obsolete and confusing.
Good comments should describe why you writing code instead of duplicating what code is doing.
XML comments, starting with ///, will get picked up by IntelliSense and it will get shown in a pop-up when looking at it from elsewhere. There is a MSDN page explaining how it works.
They will also be picked up by numerous tools that build documentation files, etc.
From MSDN:
When you compile with the /doc option, the compiler will search for
all XML tags in the source code and create an XML documentation file.
To create the final documentation based on the compiler-generated
file, you can create a custom tool or use a tool such as Sandcastle.
http://msdn.microsoft.com/en-us/library/b2s063f7.aspx
The XML comments are used to build API documentation which is readable by external tools. IntelliSense also reads these, and uses the contents to show the docs for your code in the assistance tooltips as you type (and in the Documentation window).
The compiler (optionally) extracts all those comments and puts them in a single standalone XML file next to your assembly; this can be parsed.
The idea was to have something like JavaDoc. Unfortunately Microsoft has failed to provide a mainstream mature tool to do so.
When you create a Dll assambly Xml comments provides the dll's user some information about function or something
Code in all languages usually allows for special comments. These comments can then be parsed by a process which creates automatic documentation of the code. Many libraries are documented this way.
In C# these tools are provided by Microsoft and you use the XML comments to declare that the comment should be picked up by the documentation process - if you have one set up. The comments are also picked up by auto complete.
See also doxygen, JavaDoc for implementations for other languages. See related question Good alternatives to Sandcastle to generate MSDN-style documentation
So I use XML Comments in my code to help explain Public Methods and Public Members, another developer has mentioned that not all of my methods have XML Comments. I use the rule, if public or protected, add XML comment, if private, don't.
Does this sound logical or is there some reason why you would XML Comment a private method?
There are no strong rules about comments, but I believe that it is good to comment public/internal/protected methods.
Sometimes I comment private methods when they are not very clear. Ideally code should be self-documented. For example if you have a method like
Item GetItemByTitle(string title)
then it is not required to write comments, because it's clear enough. But if a method could be unclear for other developers, please put your comments or rename/refactor the method event if it's private. Personally I prefer to read code, not comments :) If you have too many comments code becomes hard to read. My rule is to use comments only when it is required.
If on your project you have a convenience to document all methods including private methods, then follow this rule.
It makes sense to also comment private and protected members - possible reasons include:
another developer may need to use the code and a consistent commenting approach can prove helpful;
you may want to auto-generate a help/documentation file of the source code at some point; in this case, lack of Visual Studio XML comments can result in a lot of undocumented code.
I don't really see a good reason why you would limit XML comments to public members.
I subscribe to the guiding philosophy that a method should be simple enough that its signature describes exactly what it does. That being said, this is not always possible (especially when working with legacy code) so there are situations when a header comment is useful. Such as:
The methods use is not obvious (and cannot easily be refactored)
To generate api documentation
I don't think are really any hard and fast answers here, if it feels right to comment it then comment it
I always take it as a good practice to comment all my methods as equivalent to having to explain them to someone, as I would want to have them explained to me if I did not carry knowledge as to what is happening, and why.
We develop in a small team, and this really does help with team development. More so, I regularly use my OWN comments, to figure out what the heck my though process was 3 months ago when I look at a piece of code.
Absolutely worth it to spend some time in adding comments to the top of your methods / procedures that do some interesting stuff.
The question is a little unclear as to whether you are asking:
Should private code be commented in general? or
Assuming you do what to comment private code should you use XML or standard C# comments?
To comment or not
To answer the first question, needing to comment any code is a bit of a code smell. When you run into a situation that you run across code that is hard to read an needs explaining, your first attempt to solve that should be to change (usually by renaming things) so that the code is more readable. Using comments to explain an unclear method name should be a last resort.
There are some exceptions. Public methods of DLLs shared outside the solution should always be commented.
I recommend reading Robert C. (Uncle Bob) Martin's "Clean Code" book for more details on this.
XML or C# comments
In general, yes use XML comments for methods as opposed to C# comments. The XML comments show up in intellisense. Also, the XML comments are bound to the method and if you use refactoring tools to move methods the XML comments will be brought along with the method, whereas C# comments can easily be separated from the method.
One reason not to use XML comments is if you will be publicly distributing your DLL and the XML comment file. The XML file will contain comments for all your internal and private methods. So just make sure that you're OK with your customers potentially reading any of those comments on private methods.
Lately I started using /// to comment my C# code rather than // or /* because it is just much simpler to use. Today I started wondering why there were different types and came across this SO question which states that /// comments are for generating the xml documentation.
I can't find any advice with regards to on type of comments vs another on Google and I take that to mean that it doesn't matter either way. I'm not getting any ill effects so far from using /// to comment, but I'd hate to get into a habit now just to unlearn it later. As far as I can tell, if there are no metatags in the comments it does not get recognised as being documentation (or am I completely wrong on that?)
Before I riddle my code with /// comments, is this type of commenting a big no-no? Could there be potential problems from commenting this way?
Could there be potential problems from commenting this way?
Yes. When you decide to generate your project documentation, then it will have all those commented lines as part of your XML documentation. When you compile the code using /Doc extension then it generates a document using your XML comments (///). If you have used that to comment out your code, then the document generate will consider the commented out code for your documentation.
Please see:
XML Documentation Comments (C# Programming Guide)
How to: Generate XML Documentation for a Project
There isn't any technical difference as far as code compilation goes. They're all ignored.
I believe the /// comment is more of a convention to signify that you are commenting a particular code block with XML Documentation Comments. IDEs like Visual Studio are geared to recognise the different comment type and will visually style accordingly.
Given that is general convention to use standard // or /* */ comments, there's also the potential to confuse (or, more likely, annoy) other developers who will read your code.
If you use delvelopment help tools like resharper for example mostly they offer you such a functionalities of commenting acode block either with // or with /* ... */, these commented code blocks can be toggeled using these tools, this wouldnt work for you once you have 3 slashes instead of 2.
The issue with the documentation symbols is another one, you will get comments generated in your documentation without having the control on what stayes a acomment in code and what gets into the documetnation since you have all over ///, but i guess this is an issue one can configure inthe documentation generation tool.