Posts tagged ‘ReSharper’

I love these discussions, simply because in most cases, in my opinion, it boils down to personal style. Recently I was discussing with a colleague the different ways a LINQ query could be written for the same result (the discussion was based on code for Entity Framework for .NET 3.5).

Consider the following code snippets; the first uses what has been coined as “Query Comprehension Syntax” and the second is based on Method Chains (also seen referred to as “Extension Methods”):

Query Copmrehension Syntax


var query = (from e in EmployeeSet
             from o in OrderSet
             from c in CustomerSet
             where e.EmployeeID == o.Employees.EmployeeID &&
                   o.Customers.CustomerID == c.CustomerID
             group e by new { EmployeeInstance = e, CustomerInstance = c } into result
             orderby result.Key.EmployeeInstance.LastName
             select result);

Method Chain (Extension Method) Syntax


var query = (EmployeeSet
    .SelectMany(e => OrderSet, (e, o) => new {e, o})
    .SelectMany(@t => CustomerSet,(@t, c) => new {@t, c})
    .Where(@t => @t.@t.e.EmployeeID == @t.@t.o.Employees.EmployeeID &&
                @t.@t.o.Customers.CustomerID == @t.c.CustomerID)
    .GroupBy(@t => new {EmployeeInstance = @t.@t.e, CustomerInstance = @t.c}, @t => @t.@t.e)
    .OrderBy(result => result.Key.EmployeeInstance.LastName));

Well? What is the difference?

In both cases they are trying to emulate the following SQL (albeit with a bit more beef – i.e. returning the complete entities – not just the strings):

[code lang="sql"]

select e.FirstName, e.LastName, c.ContactName
from Customers c, Employees e, Orders o
where e.EmployeeID = o.EmployeeID
and o.CustomerID = c.CustomerID
group by e.FirstName, e.LastName, c.ContactName
order by e.LastName

Ok. What is the difference?

Looking at the output we get the exact same result in both cases (when put through the following algorithm):


Dictionary<BaseEmployee, List<BaseCustomer>> retVal = new Dictionary<BaseEmployee, List<BaseCustomer>>();
string previousEmployeeName = string.Empty;
BaseEmployee previousEmployeeInstance = null;
foreach (var queryItem in query)
{
    BaseEmployee employee = ConvertToBase(queryItem.Key.EmployeeInstance);
    string currentEmployeeName = string.Format("{0}-{1}", employee.FirstName, employee.LastName);
    BaseCustomer customer = ConvertToBase(queryItem.Key.CustomerInstance);
    if (currentEmployeeName != previousEmployeeName)
    {
        previousEmployeeName = currentEmployeeName;
        retVal.Add(employee, new List<BaseCustomer>());
        previousEmployeeInstance = employee;
    }
    retVal[previousEmployeeInstance].Add(customer);
}

So? What is the difference?

And looking at it through SQL Profiler, guess what? That's right! We get exactly the same result - SQL is exactly the same!

Alright already! WHAT IS THE DIFFERENCE?

Really? It would appear to be - readability... In cases where the query is long and drawn out, most of us would be quite comfortable with the QCS format as it is closer to what we are accustomed to seeing in T-SQL; however the Method Chain (Extension Methods) format is much more compact for smaller queries - much neater in my mind.

The whole discussion came about because of the functionality of ReSharper to build the Method Chain. If you hover over a QCS LINQ query, the ReSharper "lightbulb" will appear to give you the following option:

ReSharper Convert To Methods Chain

And VOILA! You have now converted it to a Method Chain... the only gotcha is that you can't change it back (forgetting the use of CTRL + Z).

Similar discussions have appeared here and here on Stack Overflow.

<Update June 10, 2009>:I wrapped some timing around both syntaxes and this was the result:

First time run:

ExtensionMethod syntax: 00:00:01.0271109
QueryComprehensionSyntax syntax: 00:00:01.0216957

Subsequent runs

ExtensionMethod syntax: 00:00:00.0976207
QueryComprehensionSyntax syntax: 00:00:00.0917982
ExtensionMethod syntax: 00:00:00.0955029
QueryComprehensionSyntax syntax: 00:00:00.0908081
ExtensionMethod syntax: 00:00:00.0974213
QueryComprehensionSyntax syntax: 00:00:00.0970167
ExtensionMethod syntax: 00:00:00.0905830
QueryComprehensionSyntax syntax: 00:00:00.1007809
ExtensionMethod syntax: 00:00:00.0895348
QueryComprehensionSyntax syntax: 00:00:00.0965262
ExtensionMethod syntax: 00:00:00.0972316
QueryComprehensionSyntax syntax: 00:00:00.0886347
ExtensionMethod syntax: 00:00:00.1030211
QueryComprehensionSyntax syntax: 00:00:00.0927539
ExtensionMethod syntax: 00:00:00.0943354
QueryComprehensionSyntax syntax: 00:00:00.0919315
ExtensionMethod syntax: 00:00:00.0938015
QueryComprehensionSyntax syntax: 00:00:00.0908355
ExtensionMethod syntax: 00:00:00.0921636
QueryComprehensionSyntax syntax: 00:00:00.0972665

  • Share/Bookmark

On numerous projects that I have worked on, the question has always arisen on how to tackle the issue of writing unit tests for existing components that have “been around the block a few times”. Invariably the answer was to only write unit tests for the new functionality and leave what has existed “for eons” well alone – I mean, it works doesn’t it? That may be the case, however it is not long before there are changes required in one area that could well impact on “old faithful”. The other reality, in my experience, the people who originally developed the “solid” code have long since left and now the development team is “aware” of what the code does, but few will dare change it for risk of breaking it. I’ve seen some serious scaffolding go on around existing code for fear of breaking the underlying functionality.

The answer is simple and, when seen from a pragmatic point of view, quite necessary – write the unit tests for that code. It will not only be an education for the developer writing the unit test to really understand the code that is being tested, but could also lead to improving the coupling by way of using Dependency Injection.

The example I have dreamt up here is by no means problematic (nor is it a work of art), the intention is to illustrate some of the methods of actually decoupling the code and using Dependency Injection.

Before going any further we need to mention the two types of Dependency Injection that most people are familiar with: Constructor Injection and Setter Injection.

Constructor Injection

As the name implies, is where the dependency is injected via the constructor. Typically an interface is passed in to the constructor as a parameter and is used to set a member variable:

  1. public CustomerManager(ICustomerRepository i_customerRepository)
  2. {
  3.     m_customerRepository = i_customerRepository;
  4. }

As you can see the internal member variable is being set to an instance of an object that implements the appropriate interface. As for the introduction of a null, there are several approaches on this:

  • Detect the null and instantiate a related “Null” type (not a null, but a minimal class that implements the expected interface).
  • Detect the null and instantiate a known, default type.
  • Detect the null and throw an exception.

In the first two cases we would not, strictly speaking, be able to write unit tests for as they would run the risk of changing the test into an integration test – imagine that the known default type was actually the next layer that communicated directly with the DB, you will inadvertently employ the test method that we are trying so hard to avoid. The third case would be testable, but could work out to be impractical in production code – there are instances where it is better to instantiate a default instance and therefore minimize the effect on production code. With this in mind, let’s return to the example previously:

  1. public CustomerManager()
  2. {
  3.     Initialize(null);
  4. }
  5.  
  6. public CustomerManager(ICustomerRepository i_customerRepository)
  7. {
  8.     Initialize(i_customerRepository);
  9. }
  10.  
  11. private ICustomerRepository m_customerRepository;
  12.  
  13. private void Initialize(ICustomerRepository i_customerRepository)
  14. {
  15.     m_customerRepository = i_customerRepository ??
  16.         new BlogSamples.SqlRepository.CustomerRepository();
  17. }

Setter Injection

Another way of injecting dependency would be to inject via the set method of a property on the object.

Using the example above, consider setting the ICustomerRepository instance via a property instead of the constructor:

  1. private ICustomerRepository m_customerRepository;
  2.  
  3. public ICustomerRepository Repository
  4. {
  5.     get
  6.     {
  7.         if (m_customerRepository == null)
  8.         {
  9.             m_customerRepository =
  10.                 new BlogSamples.SqlRepository.CustomerRepository();
  11.         }
  12.         return m_customerRepository;
  13.     }
  14.     set
  15.     {
  16.         m_customerRepository = value ??
  17.             new BlogSamples.SqlRepository.CustomerRepository();
  18.     }
  19. }

In this example I have taken a similar stance to what was mentioned previously in the constructor injection scenario. I have treated a null instance with a default instantiation. In this case I do have my doubts as to whether it is the right approach. As soon as we start to introduce default behavior we are immediately “roping off” an area that cannot be touched by proper unit testing (i.e. the idea of isolating the class entirely from it’s resources and injection those dependencies from outside). My only argument in this method’s defense is the fact that if it was true legacy code, I would need to be very careful of the client’s that use the class I am working with – far worse than not testing an a smaller part of the code would be to break existing functionality, from the client code point of view.

In either scenario (Constructor Injection or Setter Injection) we are forcing the decoupling to occur via passing in the dependency from outside the object instance.

The best method of deciding what needs to be injected is to look at what would be implied when creating an instance of a class or calling a static method from within the class in question. If the call to the method or instantiation of a type returns a simple type that did not require any complex business logic or external resources (such as a Database or config file) then chances are you are pretty safe. If, however, an external resource was accessed, then it is an ideal candidate for dependency injection and either method described previously could be used.

Example code

The example that I have prepared involves two classes, CustomerManager and EmployeeManager. Each one accesses the Database instance of the NorthWind DB (on a SQL Server instance) and each one expose typical CRUD methods. The attached zip file contain the before and after of the changes that were made to the code in order to achieve a more de-coupled class and introduce dependency injection (Base – original code; UsingDi – employing dependency injection).

The first phase was to extract the signatures of the appropriate methods and put them in to an interface (ICustomerRepository and IEmployeeRepository).

  1. public interface ICustomerRepository
  2. {
  3.     string ConnectionString { get; set; }
  4.  
  5.     void Insert(Customer i_customer);
  6.  
  7.     void Load(int i_customerId, out Customer o_customer);
  8.  
  9.     void Update(Customer i_customer);
  10.  
  11.     void Delete(Customer i_customer);
  12.  
  13.     List LoadAllCustomers();
  14. }

Once this was done, I then set about refactoring the code that accessed the DB into it’s own assembly and class; implementing the new interface. This then meant that the original CustomerManager class method’s were reduced to essentially to everything except the database access code (in this case it turned out to be a straight call through, however you get the general idea of what the aim of the exercise was):

Before:

  1. public void Insert(Customer i_customer)
  2. {
  3.     using (System.Data.SqlClient.SqlConnection connection = new SqlConnection(this.ConnectionString))
  4.     {
  5.         using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
  6.         {
  7.             cmd.Connection = connection;
  8.             cmd.CommandText =
  9.                 "INSERT INTO Customers (CustomerID, CompanyName, ContactName, ContactTitle, " +
  10.                 "Address, City, Region, PostalCode, Country, Phone, Fax) VALUES " +
  11.                 "(@CustomerID_PARAMS, @CompanyName_PARAMS, @ContactName_PARAMS, " +
  12.                 "@ContactTitle_PARAMS, @Address_PARAMS, @City_PARAMS, @Region_PARAMS, " +
  13.                 "@PostalCode_PARAMS, @Country_PARAMS, @Phone_PARAMS, @Fax_PARAMS)";
  14.             cmd.Parameters.AddWithValue("@CustomerID_PARAM", i_customer.CustomerID);
  15.             cmd.Parameters.AddWithValue("@CompanyName_PARAM", i_customer.CompanyName);
  16.             cmd.Parameters.AddWithValue("@ContactName_PARAM", i_customer.ContactName);
  17.             cmd.Parameters.AddWithValue("@ContactTitle_PARAM", i_customer.ContactTitle);
  18.             cmd.Parameters.AddWithValue("@Address_PARAM", i_customer.Address);
  19.             cmd.Parameters.AddWithValue("@City_PARAM", i_customer.City);
  20.             cmd.Parameters.AddWithValue("@Region_PARAM", i_customer.Region);
  21.             cmd.Parameters.AddWithValue("@PostalCode_PARAM", i_customer.PostalCode);
  22.             cmd.Parameters.AddWithValue("@Country_PARAM", i_customer.Country);
  23.             cmd.Parameters.AddWithValue("@Phone_PARAM", i_customer.Phone);
  24.             cmd.Parameters.AddWithValue("@Fax_PARAM", i_customer.Fax);
  25.  
  26.             connection.Open();
  27.  
  28.             cmd.ExecuteNonQuery();
  29.  
  30.             if (connection.State == ConnectionState.Open)
  31.             {
  32.                 connection.Close();
  33.             }
  34.         }
  35.     }
  36. }

After:

  1. public void Insert(Customer i_customer)
  2. {
  3.     m_customerRepository.Insert(i_customer);
  4. }

Although the example does not show any advantage in factoring out the code to a separate assembly (effectively the class has become so lightweight that it is simply calling through to the dependant instance), it does serve to show how the resource intensive code (i.e. the code that accesses the Database) can be removed to leave the code that can be tested in isolation without the need for accessing the underlying resources.

A small note on refactoring.

I use JetBrains ReSharper in Visual Studio 2008 and since the first day I have had it installed, it has been a real godsend to my code. Apart from all of the syntax highlighting and helpful hints on problematic code, one of the best features is the refactoring. Whilst preparing the code for this blog entry I had to pull out the methods from the original Connector class into an interface. At first I was “horrified” at the prospect of cutting, pasting and pruning the code as I was unsure what I would have been left out or added.

Step in ReSharper. By right clicking on the Method name I get access to the following context menu:

ReSharper Context Menu

ReSharper Context Menu

When I select extract interfaces I get the following dialog, notice how you can even state where the code for the interface gets pulled out to:

ReSharper Extract Interface Dialog

ReSharper Extract Interface Dialog

In the next blog entry I will illustrate how we can use mocking to illustrate how we would go about doing the unit testing.

  • Share/Bookmark