Microsoft recently (on my birthday) released a tool to analyse coding structure and formatting. No - its not FxCop - StyleCop analyses syntactical formatting. Let me explain:

Background

When Microsoft released FxCop, some people cringed. I remember at my previous job when having a code review and the conversation following:

  • Consultant: "Have you FxCop'd it?".
  • Me: "No...."
  • Consultant: "Hahahah - see you in 3 months!"

Those days, for me anyway, have gone. I started to use it in my everyday coding and am now pleased I use it without a second thought.

In my position with this company, I have tried to promote its use and benefits, because it promotes good coding guidelines standard approaches to software development.

FxCop works by analysing compiled code and therefore can look into its improvements at a detailed view. This is all good, but what about coding standards for syntax!?

Overview

StyleCop is a tool written and used by Microsoft to ensure all of their code is formatted, commented and laid out in a fixed format. It has quite a rigid structure to it, but so it should. I've read lots of threads about people complaining about its flexibility, but that's the whole point of standards - they don't change (often) .

Before I provide a link, I just want to show you how much you need to do, in order to pass one of these successfully. Here is a typical piece of code:

using System;
using System.Diagnostics;
using LogicAndData;

class User {

private string _username;

public string Username
{
get { return _username; }
}

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string _password;

public bool IsCorrectPassword(string guess)
{
if (String.IsNullOrEmpty(guess))
return false;

return guess.Equals(_password, StringComparison.CurrentCulture);
}

public User(string username, string password)
{
if (username == null)
throw new ArgumentNullException(Resources.Username_ParameterName);
else if (username.Length == 0)
throw new ArgumentException(Resources.Username_ParameterEmpty, Resources.Username_ParameterName);

if (password == null)
throw new ArgumentNullException(Resources.Password_ParameterName);
else if (password.Length == 0)
throw new ArgumentException(Resources.Password_ParameterEmpty, Resources.Password_ParameterName);

_username = username;
_password = password;
}
}

Pretty standard stuff really. Okay, its missing comments but it does pass FxCop! So lets have a look at the errors generated for this class:

styleCopErrors

So, what are the problems?

  1. SA1101: If you are referring to member variables (variables at class level), then you should use the keyword "this." to be explicit (2 errors)
  2. SA1201: This is a formatting issue - the order is - private fields, constructors, properties, public methods, private methods. (2 errors)
  3. SA1309: Don't use underscores! The "this" keyword implies it. (2 errors)
  4. SA1400: Class must have an identifier instead of the default (protected internal) (1 error)
  5. SA1503: If statements must use { }, even if they are only 1 line of code (6 errors)
  6. SA1600: All classes, interfaces, methods, properties and fields (optional) MUST have an XML header for documentation purposes. (4 errors)
  7. SA1633: Related to the above, there is a preset format for the documentation for the header of the file that MUST be at the top of each file created. (1 error)

Using StyleCop

What does this improve? relating to the above:

  1. It is clearer what you are working with. You don't need to use prefixes, as by using "this" you are describing which one you are referencing anyway.
  2. This just standardises the layout of your code.
  3. For clarity. It doesn't like Hungarian notation either, but DOES allow you to add acceptable notations should you wish.
  4. Be explicit about the access type, as you may not understand the access of an unmarked class.
  5. By laying out if statements this way, you are totally consistent across your code.
  6. Documentation - who doesn't document their code!?
  7. Add a header to just clarify what's doing on, any copyright notices, authors etc.

So lets see what this looks like without any errors at all!

[40 minutes later and 3 cups of coffee].... only joking - it probably took 5 minutes, mainly because I have used it before:

// <copyright file="User.cs" company="Interakting">
//     Copyright (C) 2008 Interakting. All rights reserved
// </copyright>
// <author>Dominic Zukiewicz</author>
using System;
using System.Diagnostics;
using LogicAndData;

/// <summary>
/// The User class describes a single username/password combination. The password
/// is kept secret, but timescales limit security.
/// </summary>
internal class User
{
    /// <summary>    
    /// The username of the user.    
    /// </summary>    
    private string username;

    /// <summary>    
    /// The password of the user.    
    /// </summary>    
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private string password;

    /// <summary>    
    /// Creates a user with a specific username/password combination    
    /// </summary>    
    /// <param name="username">The username of the user.</param>    
    /// <param name="password">The password of the user.</param>    
    public User(string username, string password)
    {
        if (username == null)
        {
            throw new ArgumentNullException(Resources.Username_ParameterName);
        }
        else if (username.Length == 0) 
        { 
            throw new ArgumentException(Resources.Username_ParameterEmpty, Resources.Username_ParameterName); 
        } 
        
        if (password == null) 
        {
            throw new ArgumentNullException(Resources.Password_ParameterName); 
        } 
        else if (password.Length == 0)
        { 
            throw new ArgumentException(Resources.Password_ParameterEmpty, Resources.Password_ParameterName); 
        }
        
        this.username = username; 
        this.password = password;
    }

    /// <summary>    
    /// Gets the username of the user.    
    /// </summary>    
    public string Username 
    { 
        get 
        { 
            return this.username; 
        } 
    }
    
    /// <summary>    
    /// Checks to see if the password of the user matches that of the stored password.    
    /// </summary>    
    /// <param name="guess">The guess for the password.</param>    
    /// <returns><code>true</code> if it matches, else <code>false</code>.</returns>    
    public bool CheckPassword(string guess)
    {
        if (String.IsNullOrEmpty(guess))
        { 
            return false; 
        }
        
        return guess.Equals(this.password, StringComparison.CurrentCulture);
    }
}

So what's changed - really?

What I have noticed, is that there is a good separation of the code, a very clear layout structure and of course, forcing you to comment your methods, which I really like. You'll find that the code is clearer because of the white-space implied by the curly brackets.

It can seem quite daunting to see all of these errors, but like FxCop, once you start to take these rules onboard, you are more likely to code in this style rather than turn away from it.

Here is the link to Microsoft's StyleCop: http://code.msdn.microsoft.com/sourceanalysis/Release/ProjectReleases.aspx?ReleaseId=1047


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
When using RAND() with SQL SELECT statements, the same number is generated for all rows. This is annoying if you are trying to create test data, but I've found a way to get around this. Read on for more information.

Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

After a trip to London to visit one of my friends who works for Rightmove -  the UK's No 1 Online Housing Site and we (we meaning I) got into talking about the ways we test our code. He told me that they started to use a Test Driven Development methodology. When testing in a development environment, their test framework used something called "mock objects" - these are objects that simulate behaviour, but in reality, don't do anything! I was intrigued....

Background

One of the drawback of the development process, especially with Test Driven Development, is that there comes a stage when a large amount of code has to be written to cater for a data access layer. Your program goes from:

public class DataAccessUser
{ 
     public User Load(string username)
     {
          return new User(username);
          //TODO: Write proper load
     }
}

public class BusinessObjectUser
{
     private string _username;

     public User(string username) 
     { 
          _username = username;
     }
}

To this:

public class DataAccessUser
{
     public User Load(string username)
     {          
          if( username == null )        
              throw new ArgumentNullException("username");          
          else               
              throw new ArgumentException("username","Username cannot be empty.");
          
          string connString = ConfigurationManager.ConnectionSettings["UserDB"].ConnectionString;
          SqlConnection sqlConn = new SqlConnection(connString);

          using(SqlCommand comm = sqlConn.CreateCommand())
          {
               User u = null;
               comm.Parameters.Add("@Username", username);

               sqlConn.Open();
               
               SqlDataReader dr = comm.ExecuteReader();
               
               if(dr.HasRows)
               {
                    User u = new User(dr.GetString( dr.GetOrdinal("Username"));
               }
               
               return u;
          }
     }
}

Now, I understand this is necessary as otherwise you can't load users. But now you have to test 2 parts of the code:

  1. The constructor for the User class.
  2. The DataAccessUser.Load() method.

In effect, you've written over 20 lines of code to test 2 cases line of code - the constructor call and a method call. You've also tied yourself into a specific technology for the data access layer, when you are only supposed to be concerned with testing!

Oops... you've got ahead of yourself. Now have to write another 5 test cases just for the Data Access layer.

  1. A successful BusinessObjectsUser load.
  2. An unsuccessful BusinessObjectsUser load.
  3. A null string parameter.
  4. An empty string parameter.
  5. An exception being generated for SQL being inaccessible.

This can be quite annoying as now you're losing track of your simple little BusinessObjectsUser class and loading it. In the process, have created nearly 3 times the code just by adding one method and not testing it.

Overview

Mock objects are simply an object that simulates the behaviour of a real object. A mock object is told how to behave when passed specific parameters. The idea behind this is that you are not bogged down with the technical details of the data access layer. Instead, you concentrate on the here and now, working on what is supposed to happen, rather than what will happen. Lets have a look at this in more detail.

Firstly, mock objects simulate fully implemented objects via the use of an interface. This means that in order to take advantage of mock objects, we need to use a base interface, which our real data access layer will implement. Using the example above, this would be:

internal interface IDataAccess
{
     User Load(string username);
}

Now, we need a way of telling the application to use an IDataAccess implementation we have created, instead of using a data access layer that provides real functionality.

Why? Well we want to have control over our data access layer in development, but in stage or production environments it will use the real thing. We do this using a pattern called the Dependency Injection pattern.

Dependency Injection Pattern

This pattern uses the idea that an interface is passed into an object and then the object calls the methods on that interface. As with interfaces, it doesn't have to know how the interface works, it just calls it and get its return values. This is exactly the behaviour we want! Test Driven Development works on the basis that you know how it is going to work, so you write your test case for its expected behaviour first, check it works (which it shouldn't) and then implement it. So I'll now implement a BusinessLogic class with the Dependency Injection pattern.

NB. Note from this point on we will be looking at testing this BusinessLogic class, because this is the class that uses the Dependency Injection Pattern.

public class BusinessLogic
{
     private IDataAccess _dataAccess;

     public BusinessLogic()
     {
          //Default assignment of IDataAccess goes here
     }

     public BusinessLogic(IDataAccess dataAccess)
     {
          _dataAccess = dataAccess;
     }

     public User LoadUser( string userName )
     {
          if(userName == null)
               throw new ArgumentNullException("userName");
          else if(userName.Length == 0)
               throw new ArgumentException("userName","Parameter cannot be empty.");
          else
               return _dataAccess.Load( userName );
     }
}

So we have 3 classes now:

  1. BusinessLogic, which calls
  2. IDataAccess, which uses
  3. BusinessObjects

This creates a performant and scalable architecture, but at the cost of flexibility.

Creating a mock object

In our test class, we can now create a mock object, which will emulate a class that inherits from IDataAccess.

[TestMethod()]
public void TestUserLoad()
{
     Mockery mock = new Mockery();
     IDataAccess da = mock.NewMock<IDataAccess>();
}

We now have a working IDataAccess implementation, but it doesn't do anything at all. In the NMock framework there is a class called the Stub class, which helps us tell the interface how to react for the created instance in this method.

In this example, we'll simulate the ArgumentException, when the .Load() method is called with an empty parameter. Remember we are now testing the BusinessLogic class, not the User, or IDataAccess layer:

[TestMethod(), ExpectedException(typeof(ArgumentException)]
public void TestUserLoadEmptyParameter()
{
     Mockery mock = new Mockery();
     IDataAccess da = mock.NewMock<IDataAccess>();
     Stub.On(da).Method("Load").With(string.Empty).Will(Throw.Exception( new ArgumentException() ));

     BusinessLogic bl  = new BusinessLogic(da);
     bl.LoadUser(string.Empty);

     Assert.Fail("ArgumentException has not been thrown!");
}

So how is this working? The BusinessLogic is using our "mock" IDataAccess interface, that we passed into the constructor. It is told to throw an exception when string.Empty is passed into the "Load" method. Simple!

I'll write a second test to check for a null parameter, a 3rd test to check for a valid user, and a 4th test for an invalid user. Remember, we are simulating the behaviour!

[TestMethod(), ExpectedException(typeof(ArgumentNullException)]
public void TestUserNullParameter
{
    Mockery mock = new Mockery();
     
    IDataAccess da = mock.NewMock<IDataAccess>(); 
    Stub.On(da).Method("Load").With( new object[] { null }).Will(Throw.Exception(new ArgumentNullException()));

    BusinessLogic bl = new BusinessLogic(da);
    User u = bl.LoadUser(null);

    Assert.Fail("ArgumentNullException should have been thrown!");
}

[TestMethod()]
public void TestValidUser
{
    Mockery mock = new Mockery();
     
    IDataAccess da = mock.NewMock<IDataAccess>(); 
    string username = "Billy";
    User u = new User(username);;

    Stub.On(da).Method("Load").With( username ).Will(Return.Value(u));

    BusinessLogic bl = new BusinessLogic(da);
    User u = bl.LoadUser(username);

    Assert.IsNotNull(u);
    Assert.AreSame(u.Username, username,"Usernames should be the same.");
}

[TestMethod()]
public void TestInvalidUser
{
    Mockery mock = new Mockery();
     
    IDataAccess da = mock.NewMock<IDataAccess>(); 
    string username = "Billy";

    Stub.On(da).Method("Load").With( username ).Will(Return.Value(null));

    BusinessLogic bl = new BusinessLogic(da);
    User u = bl.LoadUser(username);

    Assert.IsNull(u);
}

If you decided that you did have an IDataAccess implementing class, then you could create a method to automatically get this instance an plug it in as needed, instead of creating the mock object each time.

Real Implementation

Now, all you have to do is implement you IDataAccess interface with a real class, which would carry out the proper database access. The NMock framework and Dependency Injection pattern you have implemented gives you an excellent starting point for the expected behaviour of each method to IDataAccess.  This would have to be tested with unit tests too.

Confused?

At this point, you might be asking "What is the point? You aren't testing any data access!" and you are absolutely correct. This was the point that I stumbled over. The thing is, you would normally spend time writing your data access layer, but you would have to write tests to test this separately anyway! Unit testing is always about testing that a specific method is working in isolation. Even though our BusinessLogic.LoadUser() calls IDataAccess.Load(), we don't really care. What matters for this specific test,  is if the BusinessLogic.LoadUser() method is working and that it's working correctly in each of the 3 cases.

Summary

The NMock framework gives developers and testers an excellent starting point to development any object through the use of interfaces and easily customized behaviour within 3 lines of code.

The only cavaet of this, is that you MUST start using this as soon as you start development. Moving your project to an interface based approach can, although improve the testability of your code through the NMock framework, can easily get developers totally side-tracked. I wouldn't recommend moving to this if you are already in full flow.

I can assure you that from my experiences with it, that is an excellent example of self documenting code: short, yet descriptive and sets the building blocks in place for even the most complex of test cases.

Extra-credit

Another little tip is that some test frameworks are implemented as a separate project or assembly. The internal keyword does not allow any methods to be exposed outside of the assembly. Therefore, you need to add an attribute in your AssemblyInfo.cs to allow another namespace to access the internal methods:

[assembly: InternalsVisibleTo("AssemblyName")]

You are then able to access the internal constructors and methods of the referenced assembly.


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

I don’t know about you, but when I’ve seen some string comparisons, some people use:

string text = GetStringFromDB() 
 
if( text != string.Empty ) 
    DoThis(); 

This looks good, but its actually quite a long running process, as the CLR has to compare both strings character by character. It is much better to use String.IsNullOrEmpty to cater for this, or use .Length == 0 property, as this never changes and is computed when assigned. Here is what the String.IsNullOrEmpty method looks like:

public static bool IsNullOrEmpty(string value)
{
    if (value != null)
    {
        return (value.Length == 0);
    }
    return true;
}

If you use != , or  ==, or .Equals() the method, it uses some hefty pointer manipulation like this:

public bool Equals(string value)
{
    if ((value == null) && (this != null))
    {
        return false;
    }
    return EqualsHelper(this, value);
}
 
private static unsafe bool EqualsHelper(string strA, string strB)
{
    int length = strA.Length;
 
    if (length != strB.Length)
    {
        return false;
    }
 
    fixed (char* str = ((char*) strA))
    {
        char* chPtr = str;
        fixed (char* str2 = ((char*) strB))
        {
            char* chPtr2 = str2;
            char* chPtr3 = chPtr;
            char* chPtr4 = chPtr2;
            while (length >= 10)
            {
                if ((((*(((int*) chPtr3)) != *(((int*) chPtr4))) || (*(((int*) (chPtr3 + 2))) != *(((int*) (chPtr4 + 2))))) || ((*(((int*) (chPtr3 + 4))) != *(((int*) (chPtr4 + 4)))) || (*(((int*) (chPtr3 + 6))) != *(((int*) (chPtr4 + 6)))))) || (*(((int*) (chPtr3 + 8))) != *(((int*) (chPtr4 + 8)))))
                {
                    break;
                }
                chPtr3 += 10;
                chPtr4 += 10;
                length -= 10;
            }
            while (length > 0)
            {
                if (*(((int*) chPtr3)) != *(((int*) chPtr4)))
                {
                    break;
                }
                chPtr3 += 2;
                chPtr4 += 2;
                length -= 2;
            }
            return (length <= 0);
        }
    }
}
 

So in essence, don’t use != because

  1. It is massively slower
  2. It doesn’t take culture into consideration.
  3. It caters for 2 cases instead of 1 – what would you do if the string was null?

Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

When catering for null values, I use the ternary operator ?, which is used to do an inline IF statement. For example:

public void CheckText(string text)
{
    if(String.IsNullOrEmpty(text))
    {
        throw new ArgumentException("Parameter is " + (text==null ? "null." : "empty."));
    }
    
    //Other code here
}

This would allow you to cater for 2 exception cases:

  1. When the parameter is null, the exception message states "Parameter is null.";
  2. When the parameter is "", the exception message states "Parameter is empty.";

Since testing for null is a fairly common operation, and also catering for the possibility of a null, there is an operator called the null coalescing operator. The operator is used to check a value for null, and return an alternative value if the result is null

Before:

string text = ReadFromDB();
 
if(text == null)
    Console.WriteLine("(null)");
else
    Console.WriteLine(text);

After:

string text = ReadFromDB();
 
Console.WriteLine( text ?? "(null)" );

So, the way it works is it checks the first variable. If it is not null it returns the first variable, otherwise it returns the second. It is a shorthand method of this made up method:

public static object GetObject(object o, object _default)
{
     if( o == null )
          return _default;
     else
        return o;
 
    //Or return (o==null?_default:o);
}

The main use of this would be for outputting data to a table, or to a stream - but it looks like something I will definitely use in the future, instead of my long winded ternary operators ?


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
Want to create your own type-safe sections for reading data from the Configuration File? How about creating a class that maps directly to it with minimal code? Read this article to find out more.

Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

In the first part of this article, I discussed the option of calling multiple web services and waiting for them to all return.

It turns out you can do it quickly with a method call that already existed:


public List GetProducts( int[] productCodes )  
{
     ArrayList asyncStore = new ArrayList();
     List<int, ProductWebService.Product> products = new List<int, ProductWebService.Product>(); 
     ProductWebService.Products service = new ProductWebService.Products();
 
     service.GetProductDataCompleted += new GetProductDataCompletedEventHandler(GetProductData_Completed);
     GetProductDataDelegate asyncCall = new GetProductDataDelegate(service.GetProductData);
 
     foreach(int productCode in productCodes) 
     { 
          IAsyncResult result = asyncCall.BeginInvoke(productCode,null,productCode);
          asyncStore.Add(result.AsyncWaitHandle);
     }
 
     WaitHandle[] waitHandles = (WaitHandle[])asyncStore.ToArray(typeof(WaitHandle[]));
     WaitHandle.WaitAll ( waitHandles );
 
     //Once here, we can guarantee all of the web services have fired!
} 
 
protected void GetProductData_Completed(object sender, GetProductDataEventArgs e) 
{ 
    //Single web service fired
}

 

Therefore, you can use WaitAll() for your web services!


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

I used a ASP .NET CompareValidator to validate a floating point amount in a textbox.

While testing the application, I noticed that "0.05" would work, but "0.052", "0.0521", "0.05213" wouldn't? They were all valid numbers, but for some reason the validator was saying it wasn't?

Its turns out that theconfigured Currency data-type only allows the regional default of decimal places. Since the Regional Settings was for UK and the decimal places were 2, it wasn't technically a valid currency over 2 decimal places.

Instead I used the Double data-type to validate against, and then cast that to a decimal.

Hope this helps, as it totally baffled me!


Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist

When doing some performance testing, I used to use the DateTime and TimeSpan classes to retrieve the time elapsed - similar to this example:

public static void PerformLongOperation()
{    
    DateTime start = DateTime.Now;    
 
    //Long running operation    
    Thread.Sleep(1500);    
 
    DateTime end = DateTime.Now;    
    TimeSpan elapsedTime = end - start;    
    Console.WriteLine("Operation took {0:F2} seconds to complete.", elapsedTime.TotalSeconds);
}

Okay, so its not THAT bad is it really. So lets just check what happens when the measurement is very minute:

 

public static void PerformLongOperation()
{    
    for (int iteration = 100; iteration > 0; iteration-=5)    
    {        
        DateTime start = DateTime.Now;        
 
        //Long running operation        
        Thread.Sleep(iteration);        
 
        DateTime end = DateTime.Now;        
        Console.WriteLine("Iteration {0}: Time Taken = {1:F1}ms",iteration,(end-start).TotalMilliseconds);         
    }
}
 

 

Before running this, I would have guessed that the output would be something like:

Iteration 100: Time Taken = 100