I'm looking for a rather arbitrary answer, so this might more be a discussion. I'm wondering what the best practise for commenting my C# code in visual studio is. Right now I'm using the triple /// to generate the xml and use sand castle to build a chm or html file. But my problem is that I use code comments for two reasons:
When other developers are using my code they can read the documentation, both intellisence and the chm. or html file.
But I also use commenting as reminders to myself. So I can remember my thoughts when I come back half a year later, to some complex methods.
How can both goals be accomplished without interfering with each other, and in the same time be a quick task, not taking a lot of coding time?
The best advice I can give you is:
Don't comment bad code; rewrite it!
If methods are very complex, most of the time you are doing something wrong (not always, but very close to always). Writing readable code is hard, but it pays of, because writing good comments that you (or your colleges) will understand a year later is hard as well (and perhaps even harder). Ways to make things clear is by breaking methods up in smaller well named methods and using very clear variable names.
A book that has helped me a lot in creating better code was Robert Martins Clean Code. If you haven't read it, please do. And let all the developers in your company read it.
Good luck.
Use /// comments to document your public and protected API. Use <remarks> to describe how your API should be used. The audience of these comments are other developers using your code.
Use // comments to comment your code whenever the code alone isn't adequate to fully understand what is going on. The audience of these comments are yourself perhaps three months out in the future or another developer going to maintain your code. You can use special comments like TODO or BUGBUG to flag codes you have to revisit.
I combine both commenting styles - /// for 'public' documentation on classes, methods, etc, and // on 'private' comments for myself or the coders that follow me to read.
Related
I wrote an app in which there is a ton of comments.
This may be a bit unusual, but I would like to know if there is a way in Visual Studio to elegantly arrange the comments in a dedicated file. Or, is there a way to write text somewhere in a text file?
It is true that using comments is great, but my code is still congested.
Currently I plan to use a new class for comments, which will only contain comments with details on the parts of the code that are concerned.
If you have a better idea, thank you very much for sharing it.
I can't stress enough how much of a bad idea this is.
Code comments are best:
Being near the code they concern
Short and simple
Used sparingly - code often changes, comments can very quickly fall out of sync with this, and then before you know it the comments are doing more harm than good.
If there really is some functional explanation you're trying to get across, e.g. why something is needed and how it works, rather than how to use it, I'd recommend writing a document to explain this.
There are all sorts of ways to do this:
Word documents on a shared system (e.g. a network drive / sharepoint)
A wiki system online / internally (e.g. Atlassian Confluence, or GitHub wiki)
(to name a couple)
As per other user's suggestions though, you should ensure that there aren't a lot of comments as they just add noise (something you're clearly discovering).
Sidenote: I once worked for a company that insisted on using comments everywhere, every function had to have a banner comment with its name, signature, who wrote it and an edit history (even though we used source control), and nearly every line of code had to be commented to state what it was (supposedly) doing. If you're in a similar position, perhaps try to explain the problems this causes?
The whole point of GhostDocs is obviously to document your code. It asks you to name your methods well to do so. With well named methods however, theoritically shouldn't they be useful enough to be considered documentation?
I just want to hear some pros/cons of current users as I don't want to download it and clutter up my code with unnecessary and duplicating documentation.
While self-documenting code helps, if it were all you needed nobody would ever consult MSDN (which is, by the way, an expanded, language-merged HTML form of the XML documentation in the .NET libraries themselves).
XML-doc comments allow you to describe classes, methods, parameters, and other members more verbosely than you'd ever want to do with an identifier. You can recommend best practices, discourage incorrect or "hack-y" uses of your code, detail what could go wrong and why, etc etc. This information is available when your source code isn't (if you compile it properly), and is invaluable when your code isn't quite as self-documenting as you think (many things you might think obvious are because you think a certain way, and not everybody will think the same way).
We have a Visual Studio 2010 solution that contains several C# projects in accordance with Jeffery Palermo's Onion Architecture pattern (http://jeffreypalermo.com/blog/the-onion-architecture-part-1/). We want to add the Visual Studio Intellisense Comments using the triple slashes, but we want to see if anyone knows of best practices on how far to take this. Do we start all the way down in the Model in the Core project, and work up through Infrastructure and into the DataAccess Services and Repositories, and into the User Interface? Or is it better to use these comments in a more limited fashion, and if so what are the important objects to apply the Intellisense Comments to?
Add them to any methods exposed in public APIs, that way you can give the caller all the information they need when working with a foreign interface. For example, which exceptions the method may throw and other remarks.
It's still beneficial to add these kinds of comments to private methods, I do it anyway to be consistent. It also helps if you plan on generating documentation from the comments.
While, technically, there is such a thing as too much documentation, 99.99999% of the time this exception doesn't apply.
Document everything as much as you can. Formal, informal, stream of thought..every scrap of comments will help some poor soul who inherits your code or has to interface with it.
(It's like the old rule "The error may be in the Compiler and not your code. Compilers have errors too. This is not one of those times.")
Do we start all the way down in the Model in the Core project, and work up through Infrastructure and into the DataAccess Services and Repositories, and into the User Interface? Yes
Or is it better to use these comments in a more limited fashion, and if so what are the important objects to apply the Intellisense Comments to? If you want to. Apply them to any function you write, and not what VS autogenerates
I've seen limited "intellisense" comments..but extensive in-code comments that follow. So long as the "content" is there, life will be good. I generally include a brief blurb about each function in the intellisense comments, but put the majority of "here's why i did this" in the function and dead-tree documents.
I agree with fletcher. Start with public facing classes and methods and then work your way down into private code. If you were starting from scratch I would highly recommend adding the XML comments to all code for your own convenience, but in this case starting with public methods and then updating other classes whenever you go in to update them is a good solution.
For those of us that have programmed enough I’m sure we have come across many different flavours of coding standards that you can use when it comes to programming.
e.g. http://msdn.microsoft.com/en-us/library/ms229042.aspx
You might derive your coding standards for the current company you work for or from the original author of the code you’re working on. Coding styles are often used for specific program languages and some styles in one coding language might not be considered appropriate for others. Of course some coding standards can be applied across many different program languages.
Thank you for your time.
EDIT: As we know there are many related articles on this subject, but C# Coding standard / Best practices in SO has some very useful links in there which is worth a visit. (Check out the 2 links on .NET/C# guidelines by ESV - Accepted Answer)
Google has a posted style guide for C++ here which I consult sometimes. Just reading through the explanations and reasoning, despite whether you end up agreeing with some of the styles or not, may teach you some things you might not have thought about.
My best advice regarding coding standards: don't let them get in the way when trying to get work done.
A big bureaucracy might actually hinder progress in projects instead of helping to achieve better team work. When people complain about not following coding standards instead of the actual quality of the code, then it is too much regulation.
Other than that, pick one from the many suggestions and try to stick with it for as long as possible to build a code base following a single standard that you are used to.
Coding standards are good, but coding standards written from scratch in which the company reinvents the wheel, or coding standards imposed by a single "prophet", can be worse than having no coding standards at all.
This means:
Coding standards should be discussed and agreed upon.
The coding standards document should include the reasons behind each rule.
Coding standards should be at least partially based on reliable sources.
The sources I know of for the languages in your tags are:
For C++: The book C++ Coding Standards by Sutter/Alexandrescu.
For C#: 4 or 5 PDF's I found googling for C# Coding Standards :)
Adam Cogan has a great set of rules on his web site. There are coding guidelines, but there is much more there also.
Adam Cogan's Rules to Better...
Coding standards are great. We've been using Lance Hunt's C# Coding Standards for .NET almost without modifications
If you are maintaining code that continue to use the same standard as the original code was developed in (there is nothing worse then trying to debug a problem when the code looks all higgildy piggeldy)
Some comment to the post suggesting looking at the Google C++ guidelines. Detailed discussion about some aspects of these guidelines are posted at comp.lang.c++.moderated.
Some weird or controversial points include:
We don't believe that the available
alternatives to exceptions, such as
error codes and assertions, introduce
a significant burden.
As if assertions were a viable alternative... Assertions are usually for programming errors and situations that should never happen, while exceptions can happen (are somewhat anticipated) in the execution flow.
Reference Arguments: All parameters
passed by reference must be labeled
const. ... In fact it is a very strong
convention that input arguments are
values or const references while
output arguments are pointers.
No comment, about weasel phrase a very strong convention.
Doing Work in Constructors: Do only
trivial initialization in a
constructor. If at all possible, use
an Init() method for non-trivial
initialization. ... If your object
requires non-trivial initialization,
consider having an explicit Init()
method and/or adding a member flag
that indicates whether the object was
successfully initialized.
Yes... 2-phase init to make things simpler... What if I have const fields? This rule is probably the effect of attitude towards exceptions.
Use streams only for logging
Which streams? IOStreams, standard C streams, other?
On one hand they advise to use macros only in exceptional situations, while they recommend using DISALLOW_COPY_AND_ASSIGN to prohibit copy/assign. They could have advised the approach with special class (like in Boost)
Do not overload operators except in rare, special circumstances.
What about assignment, or arithmetic operators for numeric calculations, etc?
Default parameters are more difficult to maintain because copy-and-
paste from previous code may not reveal all the parameters. Copy-and-
pasting of code segments can cause major problems when the default
arguments are not appropriate for the new code.
The what? Copy/paste from previous code?
Remember that reading any of the guidelines can introduce a bias to your way of thinking. And sometimes it won't be beneficial for you or your code. I agree with some other posts advising reading good books by good authors beforehand. When you have sufficient amount of knowledge, then you are able to look at the guidelines and find good and weak points easily, without creating a mess in your brain ;)
If you plan to introduce a code-formatting standard to an existing programming team, get input from each member of the team so they'll have "buy in" and be more likely to write code to that standard.
Programming styles are as difficult to change as habits, and you'll have to accept that some people won't make their code 100% compliant 100% of the time. It would be worth your time to find (or write your own) pretty-printer program and periodically run all your code through it to enforce consistency. (I always felt uneasy when manually checking in source code changes that only consisted of formatting corrections for other peoples' code; I worried that others would label me a nitpicker.)
Sun Java Code Conventions
Python Style Guide
Zend Coding Standard for PHP
Having asked this question. I found that the accepted answer proved to be sufficient for my needs.
However, I realise that this is not a 'one-size-fits-all' scenario, so there is a large quantity of information within the thread that you may find more or less useful. Weel worth a read!
For Java and other C-family languages I recommend Sofware Monkey's coding standards (of course, since they're mine).
In general, keep them simple, and provide examples and justification for every requirement.
What's in the standard doesn't really matter all that much. What matters is that you have one, and that your developers follow it.
It doesn't quite answer the question, but it's worth a mention...
I read Steve McConnell's Code Complete. Whilst it doesn't give you a pre-baked set of coding standards it does set out a lot of good arguments for the various approaches. It'll make you think about things you'd not thought of before.
It changed my little world for the better.
Coding standards themselves are great and all, but what I think is much, much, MUCH more important is keeping with the style of whatever code you're maintaining. I've seen people add a function to some class written one way and forcing their coding standard on just that function. It's inconsistent, it sticks out, and, in my opinion, it makes it harder to enjoy the class "as a whole".
Whenever you're maintaining code, look at the code around it. See what the style is. K&R braces? Capital Camel Case methods? Hungarian? Double-line comment blocks between every function? Whatever it is, you should do it too in that specific area.
Before I leave, one thing I'd like to note that's related - naming files. I'm mainly a C++ guy, so this may not apply to whatever else, but basically it goes _.h or .cpp. So, Foo::Bar would be in Foo_Bar.h. Common things (i.e. a precompiled header) for the Foo namespace would be in Foo_common.h (note the lowercase common). Of course, that's a taste thing, but everybody who has worked with this has come out in favor of this.
i think Code Craft - The Practice of Writing Excellent Code pretty much sums it all up
Very popular are Ellemtel rules for C++.
For C# I recommend Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition) (Microsoft .NET Development Series).
Mono Coding Guidelines
The answers here a pretty complete, thus I am not pointing to another coding standard document. However, once you decided to stick to one style you should use an automated coding style enforcer throughout your team.
For Java there is checkstyle and for .NET Microsoft Style Cop.
Here is a similar discussion on Stackoverflow: C# Coding standard / Best practices
Camel and pascal casing alone solves a lot of coding standard problems
Over the years as I have gone through school and been working in the industry I have often asked people for advice on commenting. Sadly, as we all know, commenting with many developers is something that is taken as a side note and not much else. With that said I usually get a fairly general answer. Really this does not help much to see what will really help as time goes on.
So, what do you think is the best way to structure C#, with Visual Studio, commenting?
At the very least, I would comment all parts of your public API, using a triple-slash XML comment block. This will make it easy to auto-generate documentation if and when the time comes.
Beyond that, I would comment any particular algorithms or pieces of code which are going to be hard to decipher in six months time. This 'selfish' approach to commenting (i.e. assume you'll have to maintain this code later) often leads to the best balance of ample documentation without overkill.
I try to follow some basic guidelines when writing comments.
Comments should be simple
Comments should provide clarity
Write documentation before you write implementation
Document why you're doing something, not what you're doing.
Use built-in (XML-style) comments for interfaces, methods, properties, and classes.
Provide a summary at the top of every file (e.g., Something.cs) with the file name, description, development history, and copyright information
Add comments for bug fixes (with bug number, if appropriate)
Make use of helpful annotations like //TODO //BUG and //BUGFIX
Don't comment out code unless you plan to use it
Add comments above the line(s) of code they apply to, not to the end of the line
Try to limit comments to a single line
Use // instead of /* */ for multi-line comments
Be clear--do not use "foo," "bar," etc.
Follow casing rules where appropriate (i.e., camelCasing and PascalCasing)
"Plenty and often"
--Bilbo, The Hobbit.
More seriously, comment things that are not obvious, and tell the reader what the goal of the code is, and perhaps why you chose it.
That's not going to change based on language.
Personally I use a combination of triple slash, SandCastle XML comments and inline comments for more complicated sections. Comment often but keep it concise, nobody needs to read reams of fluff before then can figure out what something does :-)