How can I add "comments" that don't become part of the code base? - visual-studio

Often when I am learning a new technology, I like to add verbose comments everywhere, so that if I come back and am confused about something, I can refer back to the comments. However, sometimes comments and certain frameworks (ahem React) don't mix well.
I'm looking for, perhaps an extension of some sort, that will allow me to place comments in Visual Studio that will never get placed in the actual source code. Something a la commenting in Excel.

I think that is a kind of complicated to find, an easy alternative that you can try are the #regions on C# to hide/ show your comments:
#region comments
/**
* Some comments here
*/
#endregion
public void myMethod(){
//TODO
}

Related

Sectioning off code with comment blocks for readability. Good or bad idea?

So I recently started programming and sometimes I feel to need to separate my code with comment blocks like this:
//===============================================================================
//Constructors
//===============================================================================
*constructors*
//===============================================================================
//End of Constructors
//===============================================================================
For example, I might have a "Constructor" section and a "Getter/Setter" section, or a "Ok Button Implementation" section with all of OK Button's configuration, click listeners etc. This allows me to quickly scroll through a giant list of code but still be able to quickly tell that "this entire block of code are constructors" without actually looking at the code/comments of each method.
I know there is also code folding which I actually use in conjunction with comment blocks (I surround the comment blocks with a custom folding region). The reason I do that is because Code Folding is great when all code is folded, but when code is expanded, they don't stand out like a giant comment block can. So I use one to cover the case when all my code is minimized and the other to cover the case when all my code is expanded.
However, this is not a practice that I see used much so I am wondering if it is considered bad coding practice or something. I mean, this definitely helps the readability of my code to ME, but I also wouldn't want prospective employers to dock points for a weird coding style.
There is always a practice being used in coding languages like for JAVA you may see as follows:
/**
Author : Gary
Method : testMethod
Parameters : param1, param2
Exception : ArrayOutOfBound, Exception
Description : It is a dummy method
*/
public void dummyMethod(int param1, double param2) {
//Sample Method Body;
String abc = callDummyMethod();
}
You can add on your part to the existing practice to enhance it even more for yourself, and it shall also be the ease to other programmers if you find need for your code to be reviewed/debugged by them.
PS: Single Line comments(//) are never encouraged in this form.

Can VisualStudio adjust newline and formatting settings each time a file is opened?

I'm working with a small team, and we're fairly evenly split between the following styles:
public void Method() {
// code
}
and:
public void Method()
{
// code
}
I know we can each setup Visual Studio (2010 Professional) to place New Lines where we want them, but that's only at the time the code is authored.
Is it possible to have the code re-formatted when it's opened (or by running an External Tool?) to the current user's preference, or do we really need to have a long debate about the best style (or abandon any hope of consistent code)?
(note: I am NOT asking which style is best, please don't try answering that question. Just can we have VS eliminate the debate by automatically re-formatting existing code into the style preferred at the moment?)
Thanks for any help!
You can create an envrimental events macro to do just that. This link tells you how to create one of these macros.
Private Sub DocumentEvents_DocumentOpened(ByVal Document As EnvDTE.Document) Handles DocumentEvents.DocumentOpened
DTE.ExecuteCommand("Edit.FormatDocument")
End Sub

Coding-style: How to improve coding-styles and standards at a company

What are the best ways to improve the standards of coding-styles at a company? Let's use C# as an example here.
I guess there are many differences between developers that need to be taken into consideration. The concrete ones could be education, experience and past programming-languages.
How does one justify that something is right over something else?
One person may say "I move my body to the place where I earn my money with my 4-wheeled vehicle". So why is it more "right" to say "I drive to work in my car"?
Some people might like code more explicit with more lines of code. Some might like more tight code.
// Explicit
string text = defaultValue;
if (string.IsNullOrEmpty(text)) {
text = fallbackValue;
}
// Tighter
string text = defaultValue ?? fallbackValue;
Or the old protective programming-style, where you check for error-cases in the beginning and not wrap the whole method body inside a positive if-clause:
public string ChangeText(string text)
{
if (!string.IsNullOrEmpty(text))
{
// Do a lot of stuff
}
else {
throw new Exception();
}
}
// vs.
public string ChangeText(string text)
{
if (string.IsNullOrEmpty(text)) {
throw new Exception();
}
// Do a lot of stuff
}
Is the old "I'm having troubles reading this code" valid here? It's the same situation that was when Generics was introduced to C#, people had an initial trouble reading it.
Where is the line drawn between unreadable code and code that some developers are not used to?
Which part of Phil Haacks "7 Stages of new language keyword grief" has valid points here?
Are there any easy ways to set coding-standards and uphold them in a company?
UPDATE: Take in consideration things like variable-naming, that can't really be defined in a document. Or can it?
The easiest way to set coding-standards at a company:
Create a Standards Document and enforce it.
...people love to complain about code quality, but few will sit down and take the time to create a standards document. It's worth the effort and as long as you can enforce it (code reviews, etc.) then you're bound to notice an improvement in your code.
You always can use free tools like StyleCop from Microsoft.
You can disable or modify rules you don't like
There are two main sides of coding style:
"Where do I put the opening brace?" type issues - These are usually unimportant, i.e. there are no real reasons to prefer one style over the other.
Actual coding rules, like do we use return's in the middle of a function.
The way I see it, for #1 type issues, there is no point in any debate. Just set a standard in a standards document, and enforce it (more on this later).
As for the second issue, I'm honestly not sure whether it should be regulater. I personally love sprinkling functions with return values to check for error conditions, and I know some people who cringe at the practice. But at the end of the day, we can usually read each other's code just fine. These kinds of issues are much more about how you prefer expressing yourself, what is easier for you to write, and I wouldn't want a company making rules that get to this level.
As for how to enforce things, standards documents are good, but in my experience, are just never read or followed closely, and are soon forgotten. The best way is to have some kind of automated tool which tells you that you're violating the standard.
For example, even as a completely new Java programmer, I knew when to uppercase/lowercase my identifiers, simply because Eclipse let me (quietly, unobtrusively) know what the standard is.
First, you will always have to enforce the coding styles - there will never be a consent.
That's, why I would try to automate the check for consistency. Depending on your language you can use StyleCop (for .Net) or something like indent under linux.
Every developer can work with his own code style in his environment (the reformat can be very easy, depending on your environment), but all checked-in code has to be of the company's style.
Which style do you choose? Well, often there are already popular styles - depending on the language. For your example (C#) I would choose the Microsoft style. At last: only the project manager (senior programmer) has the right to adjust it.
Most companies use Coding-Style-Guidelines/Conventions. These are documents telling that you should always do braces around the if body even for one command, that you should indent with tabs/spaces, and so on.
There are a lot of tools for (automatically) check and enforce the coding-style. (An example for the java-world is checkstyle, which can be integrated into eclipse and also in a continuous integration solution like 'hudson'.)
How does one justify that something is
right over something else?
Easy: just don't. Pick a coding style, communicate it, and enforce it.
I think consistency is important here. There's not a lot of point in getting into a semantic debate over which way is better than the other unless the current methodology is particularly bad.
What is important is that the team writes their code consistently so that if someone resigns or gets hit by a bus then his/her colleagues know what is going on with the code when they are forced to work with it.

Are there standard formats for comments within code? [closed]

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.

What are your "hard rules" about commenting your code? [closed]

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.

Resources