Quality makes the application masterpiece and it's the responsibility of the developers to focus more on high quality coding. This document covers few recommendations to leverage the quality,how to avoid bad coding in .NET by using FXCop 1.30 and how to write custom rules through introspection engine.
In my view a quality software should work immaculately with zero bug, in order to make a high quality application you must consider few points such as code clarity , straightforwardness, modularity, layering, design, efficiency, best coding practices etc .The following are few recommendation/suggestions to maintain a good and quality application
- Make your coding very simple i.e. don't do activity in ten lines what you can do in five in other way you make extra effort to be summarizing it for better coding just try to minimize coding and functions that span pages. Simplicity, proper code organize, good design makes your code more reliable and bug free.
- Make your coding more clarity ( readability) for this you must write comments , follow the naming conventions ( as suggested by the document of the specific language) and give proper name to variables etc .
- Make your program modular, break your large system into small blocks which helps to make reusability of block (component).
- Make your application layering for example document view framework where some part of your application responsibility to store the data and other part renders the data and another part handles the user's inputs through menu/status bar etc .that means a higher layers call ones below, which raise events (Calls go down; events go up.) lower layers should never know what higher ones are up to. The essence of an event/callback is to provide blind upward notification. If your document calls the frame directly that means something buggy. Modules and layers are defined by APIs with proper boundaries.
- You must spend more time to define strategy for your application before implementation the thumb rule is spend 50% of your total project time for design, you should have a high level design or a low level design and Function specification and proof of concepts etc.
- Performance is one of the key factor for a quality software , this make your application faster and more economical ,try to optimize the code for better performance of course its very difficult to focus on optimization and fine tuning at implementation level but you must plan for performance at high level .The main point is you must consider the optimization and fine tuning your application in order to make a high standard application .If you do not consider the performance it leads to project failure or you have to consider additional people resource/hardware resource this again increase the project cost which leads to lose competitiveness and very important thing poor performance leads to damage customer relations.
There are lots of other points to be consider like security, design patterns (proven concepts) etc but its depends upon your application requirements. Now I am going to explain how to avoid bad coding in .NET .
Ask the expert
When ever we are talking about bad coding one tool comes to our mind that is FXCop .Those who are new to FXCop , it is a free code analysis tool (open source) from Microsoft which analyze your compiled .NET assemblies for compliance with recommended programming practices. Let me take you a brief history of FXCop .The FX in FXCop stands for Framework as in .NET Framework. Actually its original name was UrtCop (Universal Run Time ) the old name of CLR.The full name is Framework Cop and in short we call it as FXCop. The next question how and why FXCop . FXCop was created to address the goal of ensuring a consistent look and feel for a brand-new public API of .NET Framework. During the development process, it became clear the application was also useful for uncovering API usage and general correctness problems. The tool is possible due to key features of the .NET Framework that make signatures-and even Intermediate Language code itself-easily discoverable. FxCop is a case study of the time-to-develop benefits of the .NET Framework. We're pretty proud that it has achieved functionality in an extremely short development time-functionality that is similar to other tools (targeted toward unmanaged binaries).This is the way FXCop comes in picture.You can download this tool from http://www.gotdotnet.com/team/fxcop
One of the thumb rule is coding standards is around as long as the programming/development is exists. FXCop targets to .NET code only .you can operate FXCop in two mode one is through a GUI and through command-line mode . Microsoft has obviously made a huge investment in .NET and in promulgating best .NET coding practices through the .NET Framework Design Guidelines, which you can find at Design Guidelines for Class Library Developers. Internally, Microsoft wanted to make sure their own developers followed the rules for consistency and maintainability. To enforce the Design Guidelines they devised a solution, out of which sprang FxCop. FxCop aims to make it easy to comply by scanning compiled assemblies and creating a report that details coding errors (called violations) and suggests code fixes and improvements. Behind the screen FXCop usages reflection technique to read the code of your assembly and process against predefined rules ( around 200+ rules are defined ) categorized as naming conventions, library design, localization, security, performance and many more I am not explain these rules in details expect you can get it in detail from FXCop documentation. Checks the code for compliance with these rules. Most of the coding practices are also available in MSDN site for Design and Naming Guidelines refer
http://msdn.microsoft.com/library/en-us/cpgenref/html/cpconnetframeworkdesignguidelines.asp or http://msdn.microsoft.com/library/en-us/cpgenref/html/cpconnamingguidelines.asp
and for Secure Coding Guidelines refer
http://msdn.microsoft.com/library/en-us/dnnetsec/html/seccodeguide.asp
To start with FXCop lets write a sample application and run it under FXCop for check the best coding practices, have a look at the sample code.
using
System;
namespace MySample
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class sampleClass
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
private string myString = "";
private int myInterger =0;
public string myValue
{
set
{
myString=value;
}
}
public void FillIntVal(int externalValue)
{
myInterger= externalValue;
}
public int GetIntVal()
{
return myInterger;
}
[STAThread]
static void Main(string[] args)
{
sampleClass objSample = new sampleClass();
objSample.FillIntVal(10);
Console.WriteLine(objSample.myInterger.ToString());
}
}
}
Now compile the code and generate the assembly to test it in FXCop. The GUI version of FxCop has two panes that are easy to navigate. To analyze an assembly, you simply select Add Assembly from the Project menu (not File). To see the rules that FxCop will apply, click the Rules tab, which lists them by category. To make changes, click on the category name and select or deselect the rules you want to apply. The FXCop 1.30 has 6 additional new rules overall now we have 12 rules. The yellow highlighted codes are the bad coding practices .The defects are - The class name does not follow the camel casing naming convention.
- Similar the property name does not follow the camel casing naming convention.
- The next defect is consider property when its does not takes parameter and return values directly or doing minimum operation for returning the value.
- The next defect is the sample class has set property and does not has get property .
If you look at the inside of FXCop actually it usage the reflection to reading the classes in an assembly and compare the rules if the code is not compliance with the rule then its log the defects. Till now FXCop provides around 200+ rules incorporate most of the best practices .The new version of FXCop includes around 43 rules and all of them are really handy like "avoid unnecessary string creation" or "do not raise reserved exception type" etc . But some time you need additional rules specific to your project .In order to implement this FXCop provides a option to write custom rules using FXCop SDK .The earlier version of FXCop ( v1.23 ) usage reflection mechanism to scan the managed assembly but in FXCop 1.30 its totally obsolete in replace to this Microsoft introduce Introspection engine. The reason is reflection is very slow around 400 times as slow as a regular function call. One performance trick that I discovered is that a delegate can be constructed from a MethodInfo, by calling one of the Delegate static methods, allowing for a direct call to be made using the correct signature. Introspection which was described as a new faster, engine for performing Reflection on .NET classes .The main advantages of introspection engine is performs more extensive analysis then reflection , multithreading, analysis of assemblies of different versions of the framework, ability to Managed Extensions for C++ executables, and non-locking behavior. It appears that Introspection is designed for applications and tools that perform large-scale reflecting on an assembly (perhaps reading all of the metadata into memory). In such cases, reflection would need to execute quickly for good reason. So, it would not probably not provide a performance improvement for simple uses of reflection in a standard app. One drawback is SDK for introspection engine has not documented by the FXCop team . I suggest to the developers who already developed the custom rules using Microsoft.Tools.FxCop.Sdk.Reflection migrate your code to introspection engine SDK and I believe FXCop team slowly changing there existing rules to leverage the advantages of introspection engine SDK.
Now I am going to demonstrate how to write custom rules using introspection engine SDK. Below is the sample code
MyCustRules.cs
using
System;
using Microsoft.Cci;
using Microsoft.Tools.FxCop.Sdk;
using Microsoft.Tools.FxCop.Sdk.Introspection;
#endregion
namespace FxCop.MyCustRules
{
//Provides the base class for all introspection rules.
//The BaseIntrospectionRule class defines 15 different Check methods
//you can implement in your rules
[CLSCompliant(false)]
public abstract class MyBaseCustRule : BaseIntrospectionRule
{
//loading the rules.xml
// XML file name should be <namespace>.xml
//in this example its MyCustRules.xml
protected MyBaseCustRule(string name) : base(name, "FxCop.Rules.Rules", typeof
BaseRule).Assembly)
{
}
//overrides method of BaseIntrospectionRule.Check(TypeNode)
// to chekc the type of object
public override ProblemCollection Check(TypeNode type)
{
if (type == null)
return null;
switch (type.NodeType)
{
case NodeType.Class:
{
return Check((Class)type);
}
case NodeType.Interface:
{
return Check((Interface)type);
}
case NodeType.Struct:
{
return Check((Struct)type);
}
case NodeType.EnumNode:
{
return Check((EnumNode)type);
}
}
return base.Check(type);
}
// overrides method for BaseIntrospectionRule.Check(Module)
public override ProblemCollection Check(Module module)
{
if (module == null)
return null;
if (module.NodeType == NodeType.Assembly)
{
return Check((AssemblyNode)module);
}
return base.Check(module);
}
}
}
AvoidComplicated Method.cs using
System;
using System.Globalization;
using Microsoft.Cci;
using Microsoft.Tools.FxCop.Sdk;
using Microsoft.Tools.FxCop.Sdk.Introspection;
#endregion
namespace FxCop.MyCustRules
{
//Checks for complicated methods.
// lets asume if the lines exceeeds 75 lines , called as complecated method
[CLSCompliant(false)]
public class AvoidComplicatedMethods : MyBaseCustRule
// set the value as per your project specification
private const int MAXLINE= 75;
ublic AvoidComplicatedMethods() : base("AvoidComplicatedMethods")
{
}
//Overrides the check method and count the method lines
public override ProblemCollection Check(Member m)
{
Method method = m as Method;
if (method == null)
return null;
if (method.Instructions == null)
return null;
string name = method.Name.Name;
if (name == "InitializeComponent")
return null;
int methodLineCounter = 0;
for (int i = 0; i < method.Instructions.Length; i++)
{
if (RuleHelper.IsMethodCall(method.Instructions[i]))
{
methodLineCounter++;
}
}
if (methodCallCount > MAXLINE)
{
// reporting the defects
//Problems.Add method helps to log the noncompliance code
Problems.Add(new Problem(GetResolution(RuleUtilities.Format(method), methodCallCount.ToString(CultureInfo.CurrentCulture), MAXLINE.ToString CultureInfo.CurrentCulture))));
}
return Problems;
}
}
}
MyCustRules.xml <?
xml version="1.0" encoding="utf-8" ?>
<Rules FriendlyName="Custom Rules">
<Rule TypeName="AvoidComplicatedMethods" Category="Custom" CheckId="Cust1001">
<Name>Avoid complicated methods</Name>
<Description>Methods that have many methodscalls or property are hard to maintain and therefore should be kept to a minimum.</Description>
<Owner>Anand Kumar Rao</Owner>
<Url></Url>
<Resolution>'{0}' has {1} method calls. Refactor '{0}' so that it calls fewer than {2} methods.</Resolution>
<Email>E-Mail ID = anandkumar2004@gmail.com</Email>
<MessageLevel Certainty="95">Warning</MessageLevel>
<FixCategories>NonBreaking</FixCategories>
</Rule>
</Rules>
To writing the custom rules I have MyBaseCustRule derived from BaseIntrospectionRule . BaseIntrospectionRule has 15 different check method to inspect the type of objects passing to the rule and in the constructor I am loading the XML file which contains description of the rule and prompt to the user if the code is violating the rule.This XML file is very simple and you can extend as per your project requirement.AvoidComplicatedMethods class derived from MyBaseCustRule and implemented the Check method to read the number of lines present in each method of the class , checks that method should not exceed 75 lines. If it exceeds 75 lines then log the defect by calling Problems.Add(....) method of introspection engine. Conclusion
I conclude this discussion by recommending to use FXCop in your regular development to avoid bad coding and maintain quality of the application. Visual Studio Team System (VSTS) has lots of enhancements primarily focus on good coding standards and FXCop is inbuilt integrated with the VS IDE to check the code to compliance with Microsoft best practices. We will talk about in my coming article.