AgendaWhat are Coding Standards?Benefits of AutomationStandards Automation ToolsUse of StyleCop and FxCop
What are Coding Standards?A set of rules or guidelines used when writing thesource code of a computer program.Generally dictates:Safety mandates to avoid introducing errors.Style mandates to increase maintainability.Security mandates to avoid vulnerabilities.Efficiency mandates to help increase performance.Standards may be enforced through code reviews ormay simply be “suggestions”.
But, Isn’t Programming Art?This always has been an interesting point ofcontention.On one extreme development can be thought of as awork of art and any source that reaches a logicallycorrect result is acceptable and everything else is just“style.”The other extreme believes that programming is purelya mechanical process and there is only a limitednumber of correct answers.Which is correct?
Reality Lies In BetweenIt may be more accurate to say developers are morelike artisans (crafters) than artists, though containingelements of both.An artist has a wide range of forms they can adhere toand much is dependent on the interpretation of theviewer.In contrast, artisans tend to construct or design for apurpose, and while there are some elements of style inconstruction, if it fails to achieve its purposeeffectively, it is a failure.
The “Art” of SortingTake sorting, for example.Both Bubble sort and Quick sort are valid sorts on a setof data.Bubble sort has a complexity of O(n2) and Quick sort isO(n log n).Assuming sorting 1 million elements and each checktakes 1 µs, roughly this would be: Bubble Sort: 11 days Quick Sort: 19 secondsBoth sort data, but one is clearly more useful.
Standardizing an “Art”While there are many ways to solve a given problem,there should be guidelines for effective construction.These guidelines are similar to building codes used inbuilding construction to ensure safety and quality.These guidelines form the basis for coding standardsand are best compiled from group consensus andindustry best practices.
Enforcing StandardsStandards should be enforced to promote safety,efficiency, and maintainability.Standards can be enforced through Code Reviews, butthese tend to be applied with varying levels ofadherence.It’s much better to attempt to automate as much ofyour standards as possible so that the code is judgedmore objectively.
Benefits of AutomationStandards are applied objectively since only analyzesthe source or assembly.Just plain faster than trying to catch standardsviolations manually.Code authors don’t feel personally attacked.Frees more reviewer time since won’t have to waste asmuch time in code reviews.Frees more time for developers since code spends lesstime and iterations in review.
Standards Automation ToolsThere are two primary tools from Microsoft:StyleCop – Analyzes source files to determine if sourcecode is correctly formatted.FxCop (Static Code Analysis)– Analyzes assemblies todetermine if code is constructed safely and optimally.These tools overlap in some of their base rules butboth have their strengths.Other third party and Microsoft tools exist, butbeyond this presentation’s scope.
FxCop, VS Code AnalysisStatic analysisAnalyzes compiled assembly (dll, exe)Finds violations of programming and design rules http://msdn.microsoft.com/en-us/library/3z0aeatx.aspx
GendarmeStatic analysisAnalyzes compiled assembly (dll, exe)Finds violations of programming and design rules http://mono-project.com/Gendarme
StyleCopAnalyzes source files and not compiled code.Great for checking elements such as:SpacingCommentsFile compositionNamingCannot easily check type hierarchies or programstructure.Available at http://stylecop.codeplex.com/
Configuring StyleCopIf you have StyleCop installed, you can haveSettings.StyleCop files for each project if you want tovary styles per project.Will take the first Settings.StyleCop file it finds fromworking directory on up the path.Default will be the Settings.StyleCop file inc:program filesMicrosoft StyleCop…Various configurations can make harder to enforceuniform rules, though, so use with caution.
Configuring StyleCopYou can configure which base rules you want active byusing StyleCopSettingsEditor.exe.Let’s take a minute to look at the rules…
Configuring StyleCopYou can also get to StyleCop settings in Visual Studiodirectly by right-clicking a project.This creates local copy of rules, use cautiously.
Running StyleCopYou can run StyleCop from VS or MSBuild.Has no native command-line interface, but one existsat sourceforge called StyleCopCmd.
StyleCop ResultsShows in Error List window, can turn on “Warnings asErrors” in VS if you want to break builds on violations.
Suppressing a RuleMost rules are good all the time, sometimes not.
On Suppressing RulesIt’s better to keep a rule even if it only applies 95% ofthe time and force developers to suppress the rule forthe one-off exceptions.This puts a SuppressMessage attribute in codewhich must be justified and prevents viewing theexception to the rule as a precedent for ignoring therule.If code reviewer disagrees, can be debated.Turning off rules should be avoided unless the rule isinvalid most or all of the time.
Custom StyleCop RulesStyleCop rules are fairly easy to write.Create class library that references the StyleCopassemblies:Located in c:program filesMicrosoft StyleCop… Microsoft.StyleCop.dll Microsoft.StyleCop.Csharp.dllAdd a CS (C# source file) for new analyzer.Add an XML file for rule configuration.
Custom StyleCop RulesIn the CS file, create an analyzer that inherits fromSourceAnalyzer and has class attribute also namedSourceAnalyzer for C# files.s
Custom StyleCop RulesIn the CS file, override AnalyzeDocument andperform your checks.
Custom StyleCop RulesWhen you see your violation, call the methodAddViolation and give it a rule name and args:
Custom Style Cop RulesThen, in the XML file, define the rule and message.Make sure XML file has same name as class name andis Embedded Resource.
Custom StyleCop RulesThen, build the custom assembly.Place custom assembly in:C:Program FilesMicrosoft StyleCop …You should now see custom rules in theStyleCopSettingsEditor.If you don’t see custom rules, check that the XML file:Is an embedded resourceHas same filename as the class name (minusextensions)Let’s look at the code more closely…
StyleCop for ReSharperJetBrains’s ReSharper is an Visual Studio IDE plug-inthat adds a lot of refactoring and aids.StyleCop for ReSharper is a ReSharper plug-in thatallows for dynamic checking of StyleCop rules as youtype.Will highlight rule violations with squiggle just likeother ReSharper hints.http://stylecopforresharper.codeplex.com/Let’s look at how this appears in the IDE.
FxCop (aka VS Code Analysis)Great for checking elements such as:Non-spacing style issues (naming, etc).Code safety and performance issuesType hierarchy issuesAnalysis of database objectsCannot check source style such as spacing.Already baked into Visual Studio 2008/10.Can also be used as a stand-alone.
Running FxCop Stand-AloneStart Programs Microsoft FxCopCreate new project, add targets, and Analyze!
Running FxCop From Visual StudioRight click on project or solution and choose RunCode Analysis:Let’s look at an example analysis.
Suppressing FxCop ErrorsJust like in StyleCop, you can suppress one-offexceptions to the rules.Can insert manually or automatically from the errorlist in Visual Studio.
Custom FxCop RulesCreate a Class Library in Visual Studio.Add references to FxCop assemblies:From C:Program FilesMicrosoft FxCop… FxCopCommon.dll FxCopSdk.dll Microsoft.Cci.dll Microsoft.VisualStudio.CodeAnalysisAdd a CS file for the new rule.Add an XML file for the rule definition.
Custom FxCop RulesIn CS file create class that inherits fromBaseIntrospectionRule:
Custom FxCop RuleXML file is Embedded and contains rule detail:Remember filename must be same as passed to baseconstructor of BaseIntrospectionRule.
Custom FxCop RulesTo use custom rule, use CTRL+R or Project AddRules in FxCop.You can verify by clicking on rules tab:
SummaryAutomating code standards can be very useful forgetting rid of a lot of the “noise” in code reviews andallowing reviewers to concentrate on logic bugs.Automated code standards take the personal side outof enforcing style, safety, and performance.Custom rules can be used in FxCop and StyleCop toallow for your own rules.