Can I use ReSharper to enforce commenting standards? - c#

Been playing a lot recently with ReSharper and one thing I'd love to setup for my team are notifications if a C# class or C# file doesn't have a set code commenting standard. Unfortunately I have not yet been able to find much on the topic.
For example, I'd like to ensure all methods or functions have a comment description above them:
/// <summary>
/// Description of MyMethod here.
/// </summary>
public void MyMethod();
I would like to also see that a basic check for whether (Number of lines of code) / (Number of lines of comments) is around some magic happy-medium, and create a notification or warning if not.

One simple option to start with (which doesn't even need R#) is to turn on the generation of an XML documentation file, and then treat warnings as errors. That will ensure that every public member has documentation.
It won't ensure that the comments are good, of course... but it will ensure they exist.
EDIT: R# does have a setting for this - under Code Inspection, Inspection Severity, C#, Compiler Warnings, look for CS1591: Missing XML comment for publicly visible type or member (and related warnings near it). Change the severity of that to Error and it might help you - but it's hard to say as you're in an unusual environment.

Not to compete with Jon but GhostDoc does what you're describing.

Also, check out StyleCop which has a Resharper plugin, which means missing comments (for methods, properties, etc) will be shown as Resharper warnings/errors. May, or may not, be of interest for you, but at least it's an option.

There are two options. Both - using extensions for ReSharper - not for Visual Studio (if you didn't know, ReSharper has its own Extension Manager). These extensions are (use the second one!):
AgentSmith (for R#9). Now, my ReSharper's Extension Manager says, that this extension is for ReSharper of the version 9.0 (which I have installed) but, in fact, this extension works with errors (disabling of highlights works not properly).
XML Doc Inspections for ReSharper 9. Seems, works without any problems (I have it just installed). That is what you really need to highlight classes, methods, properties and so on (even private fields) that have no XML comments!

Stylecop has many rules for comments, you may also want to look at Stylecop+ as this has some extra rules for Method/Property lengths.

Related

Resharper warns about unused methods called by Unity3D

I just started using Reshaper today, and to get a lot of warnings about unused methods provided by Unity3D, like Awake(), Start()and Update() etc. Those are called by Unity3D with Reflection, Resharper cannot know that, and therefore warns about them.
Is there a better way to suppress those, then just disabling the whole "type or method is never used" warning, or adding the [UsedImplicitly] attribute to everything?
ReSharper 10 has a 'Unity Support' extension that does a great job at marking Unity's implicit MonoBehaviour functions and public variables as 'used'.
https://github.com/JetBrains/resharper-unity
You can install it direclty from inside Visual Studio:
ReSharper > Extension Manager... > Search for 'Unity' > Click 'Install' on 'Unity Support'
As #BlueRaja comments - you've pretty much listed all possible solutions. The best solution is to indeed use the [UsedImplicitly] attribute, which is a part of ReSharper Annotations. However, instead of applying it in code to your types, it would be best to annotate the base types (I'm guessing MonoBehavior? I'm sorry, I'm not familiar with Unity3D API). This way, every type you implement that derives from those, will automatically inherit the [UsedImplicitly] attribute.
The best and non-intrusive way this could be done is by External Annotations - same as code annotations, but applicable externally via XML.
There are 3 choices here: either you do this yourself (take a look at ExternalAnnotations directory, located either at
%localappdata%\JetBrains\ReSharper\vAny\packages\ReSharper.ExternalAnnotations...
since ReSharper 8.2, or
C:\Program Files (x86)\JetBrains\ReSharper\vX.X\ExternalAnnotations
in previous versions)
You can find examples of external annotations XMLs, and create one yourself, following the same naming conventions. To help you with copying method names in the correct format, you could use Copy XML-Doc ID to Clipboard option under the Edit menu in ReSharper.
This way you can annotate the Unity3D base classes, and then distribute this XML as a ReSharper extension for others' benefit.
(the other two things you can do is either convince Unity3D to do this themselves, or open an issue on ReSharper's bug tracker, and maybe JetBrains will do that. But your best bet is to do this yourself).
Hope this helps.
I usually just make them public, downside being that they then show up in the list of methods you can call from other scripts. The methods will probably also still show up grey (as in not called anywhere from within your solution) but at least you won't get the warnings any more.
The annotations thing never works for me, so this is my workaround.

C# // vs /// comments

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.

Which are the differences between StyleCop and Code Analysis when talking about the rules of each?

Could you please tell me which are the differences between rules of StyleCop and Code Analysis ? Should it be used together or not ?
Thanks.
Style cop essentially parses the file looking for formatting issues and other things that you could think of as "cosmetic". Code analysis actually builds your code and inspects the compiled runtime IL for characteristics about how it behaves when it runs and flag potential runtime problems.
So, they are complimentary, and you are perfectly fine to use them together.
Short answer:
stylecop: takes your source code as input and checks for potential code style issues. For instance: using directives are not alphabetically ordered...etc.
fxcop (now code analysis): takes a compiled assembly as input and checks for potential issues related to the executable/dll itself when it'll be executed. For instance: in your class you have a member of type IDisposable that is not disposed properly.
However, there are some rules that are common to both tools, for instance rules related to naming convention for public exposed types.
Anyway, using both is a good idea.
FxCop checks what is written. It works over the compiled assembly.
StyleCop checks how it is written. It works over the parsed source file, even without trying to compile it.
This leads to all the differences. For example, FxCop cannot check indentations, cause they are absent in a compiled assembly. And StyleCop cannot perform code-flow checks cause it doesn't know how your code is really being executed.

Are there any tools which can report on commented-out .NET code?

Has anyone come across a tool to report on commented-out code in a .NET app? I'm talking about patterns like:
//var foo = "This is dead";
And
/*
var foo = "This is dead";
*/
This won't be found by tools like ReSharper or FxCop which look for unreferenced code. There are obvious implications around distinguishing commented code from commented text but it doesn't seem like too great a task.
Is there any existing tool out there which can pick this up? Even if it was just reporting of occurrences by file rather than full IDE integration.
Edit 1: I've also logged this as a StyleCop feature request. Seems like a good fit for the tool.
Edit 2: Yes, there's a good reason why I'd like to do this and it relates to code quality. See my comment below.
You can get an approximate answer by using a regexp that recognizes comments, that end with ";" or "}".
For a more precise scheme, see this answer:
Tool to find commented out VHDL code
I've been done this road for the same reason. I more or less did was Ira Baxter suggested (though I focused on variable_type variable = value and specifically looked for lines that consisted of 0 or more whitespace at beginning followed by // followed by code (and to handle /* */, I wrote a preprocessor that converted it into //'s. I tweaked the reg exp to cut down on false positives and also did a manual inspection just to be safe; fortunately, there were very few cases where the comment was doing pseudo-code like things as drachenstern suggests above; YMMV. I'd love to find a tool that could do this but some false positives from valid but possibly overly detailed pseudo code are going to be really to rule out, especially if they're using literate programming techniques to make the code as "readable" as pseudo code.
(I also did this for VB6 code; on the one hand, the lack of ;'s made it harder to right an "easy" reg exp, on the other hand the code used a lot less classes so it was easier to match on variable types which tend not to be in pseudo code)
Another option I looked at but didn't have available was to look at the revision control logs for lines that were code in version X and then //same line in version Y... this of courses assumes that A) they are using revision control B) you can view it, and C) they didn't write code and comment it out in the same revision. (And gets a little trickier if they use /* */ comments
There is another option for this, Sonar. It is actually a Java centric app but there is a plugin that can handle C# code. Currently it can report on:
StyleCop errors
FxCop errors
Gendarme errors
Duplicated code
Commented code
Unit test results
Code coverage (using NCover, OpenCover)
It does take a while for it to scan mostly due to the duplication checks (AFAIK uses text matching rather than C# syntax trees) and if you use the internal default derby database it can fail on large code bases. However it is very useful to for the code-base metrics you gain and it has snapshot features that enable you to see how things have changed and (hopefully) got better over time.
Since StyleCop is not actively maintained (see https://github.com/StyleCop/StyleCop#considerations), I decided to roll out my own, dead-csharp:
https://github.com/mristin/dead-csharp
Dead-csharp uses heuristics to find code patterns in the comments. The comments starting with /// are intentionally ignored (so that you can write code in structured comments).
StyleCop will catch the first pattern. It suggests you use //// as a comment for code so that it will ignore the rule.
Seeing as you mentioned NDepends it also can tell you Percentage commented http://www.ndepend.com/Metrics.aspx#PercentageComment. This is defined for application, assemblies, namespaces, types and methods.

Tool to find all unused Code

I need a tool I can run that will show me a list of unused methods, variables, properties, and classes. CSS classes would be an added bonus.
I heard FXCop can do this? or NDepend or something?
Look at ReSharper.
Code Analysis in VSTS will generate warnings about this during the build process. You can set it up to treat Warnings As Errors.
You can use ReSharper to find unused code and Dust-Me Selectors to find unused CSS.
The tool NDepend can help find unused code in a .NET code base. Disclaimer: I am one of the developer of this tool.
NDepend proposes to write Code Rule over LINQ Query (CQLinq). Around 200 default code rules are proposed, 3 of them being dedicated to unused/dead code detection:
Potentially dead Types (hence detect unused class, struct, interface, delegate...)
Potentially dead Methods (hence detect unused method, ctor, property getter/setter...)
Potentially dead Fields
NDepend is integrated in Visual Studio, thus these rules can be checked/browsed/edited right inside the IDE. The tool can also be integrated into your CI process and it can build reports that will show rules violated and culprit code elements.
If you click these 3 links above toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because they detect not only unused types and methods, but also types and methods used only by unused dead types and methods (recursive).
This is static analysis, hence the prefix Potentially in the rule names. If a code element is used only through reflection, these rules might consider it as unused which is not the case.
In addition to using these 3 rules, I'd advise measuring code coverage by tests and striving for having full coverage. Often, you'll see that code that cannot be covered by tests, is actually unused/dead code that can be safely discarded. This is especially useful in complex algorithms where it is not clear if a branch of code is reachable or not.
Gendarme has also different rules to find unused code.

Categories