Showing posts with label .NET Framework. Show all posts
Showing posts with label .NET Framework. Show all posts

Sunday, 1 February 2009

Using language features for readability and understandability

Whilst pairing recently, we came across a situation that I believed was best solved using LINQ. I've not used LINQ much other than reading about it in blogs so it was an opportunity to see what it was all about. In the end, we managed to solve the problem very nicely with very few lines of code. As we continued programming, yet another opportunity arose where LINQ could have solved the problem but instead we chose to write a foreach statement and this made me stop and think about language syntax in general. Why do we chose to use a certain syntax over another? Is it readability? Is it understandability? It is about knowledge? This post explores a few thoughts around this topic.

I can think of a few reasons that might affect why a developer would chose to use a certain syntax:

  • readability
  • understandability
  • fewest lines of code
  • existing knowledge of the syntax
  • they only know one way to solve the problem
  • technical constraint (platform, deployment, etc)

These are just a few choices of the top of my head and I'll examine the readability and understandability first. These two terms are very closely related but they do have distinct differences. I'm not going to discuss them here, but you can read further on Wikipedia on readability and understandability. Suffice to say that the choice of syntax can enhance both these concepts. Let's look at an example:

public string Name

{

    get

    {

        if (name == null)

            return "No name";

        return name;

    }

}

 

public string Name

{

    get { return name ?? "No name"; }

}

These two property statements are identical in functionality but obviously differ in syntax. However, if you do not understand the '??' operator, you will be at a loss for the second statement. However, if you did understand the operator, which of the statements has a higher readability index? I've come round to thinking that they are both readable but one could argue that the first one is more understandable because it uses an explanatory if statement. However, the '??' operator explains the same thing albeit that you need knowledge of the operator to understand its function. Further, you could also argue that the second implementation is more readable because it is only one line of code to read.

Let's look at another example this time using LINQ:

public IList<Customer> GetCustomers(string startsWith)

{

    IList<Customer> customersStaringWith = new List<Customer>();

    foreach (Customer customer in customers)

    {

        if (customer.Name.StartsWith(startsWith))

        {

            customersStaringWith.Add(customer);

        }

    }

    return customersStaringWith;

}








public IList<Customer> GetCustomersLinq(string startsWith)

{

    var selectedCustomers =

        from customer in customers

        where customer.Name.StartsWith(startsWith)

        select customer;

 

    return new List<Customer>(selectedCustomers);

}



Again, these two methods return the same result but which one is more readable?



Drawing a conclusion from this is quite difficult as readability and understandability are generally opinionated views. However, what I find interesting is that there are some language syntaxes that are adopted readily whilst others are left behind. Take generics, for example. I don't know any developer that doesn't use generics if they are using .NET Framework 2.0 or above. What is it about the syntax that attracts its adoption? Are developers becoming lazy about learning new syntaxes because they can still accomplish their goals using "standard" syntax? Does using a more recent syntax (Linq, Lambda) reflect on the developer's skill or is it just demonstrating knowledge?



So that I'm not left behind, I'm trying to use these new syntaxes where I get a chance as I believe that the more you use them, the more readable they become - to you. Sometimes, developers fear new syntaxes because they don't understand them well enough to use them effectively and therefore they write them off if they can accomplish the same result in another way. If a new syntax makes for more concise code and it doesn't impair its readability, then I believe it is the right choice. One way to expose yourself to various syntaxes (and code styles) is to take part in an open source project and explore the source code.



I've only scratched the surface in this post about readability and understandability but the concepts of each are extremely important to grasp in order to write good code, IMHO.

Tuesday, 15 July 2008

Creating a custom dictionary for code analysis in VS2008

There seems to be a few posts out there asking where to put a custom dictionary to be used by FxCop (code analysis). In Visual Studio 2008, you can add a dictionary xml file to the solution and then tell the solution to use this as the dictionary for FxCop. Here's how.

Create your dictionary file
Add a new XML file to your project or solution and call it what you want. It doesn't need to be called CustomDictionary.xml.
The dictionary file must follow the correct schema, but unfortunately, there does not appear to be an .xsd schema file available (that I can find). As a starting point, copy the XML from the CustomDictionary.xml that comes with FxCop which is in the default FxCop install directory which on my machine is C:\Program Files\Microsoft Visual Studio 9.0\Team Tools\Static Analysis Tools\FxCop\CustomDictionary.xml. You can then edit this file to include your own words. However, the schema is pretty simple:


Making FxCop use your dictionary
In the properties for the XML file you've created (right-click, properties), change the Build Action to 'CodeAnalysisDictionary'.
Recompile your project and FxCop should no longer complain about those words. If you examine the build output window, Visual Studio makes a call to FxCop.exe with a whole load of parameters. Setting the build action property of the xml file to CodeAnalysisDictionary, makes VS include the switch /dictionary:"" to the FxCop command.
You can also just amened the CustomDictionaryl.xml file in the FxCop default installation directory but this obviously only takes effect on that machine. I like being able to check this dictionary file into source control so that other team members can benefit from it and this also includes the build server.

Reusing the dictionary across assemblies
Another common situation is that you have more than one assembly and you want to share the same dictionary across them. One way of doing this is to add your dictionary file to the solution rather than a specific project. Then, add an existing item to your project, browse to the dictionary file in your solution, and select add as link. This add the dictionary file to your project and makes the link act like a shortcut to the dictionary file in your solution. This means you only physically create one dictionary file which is then easily shared across all your assemblies. Remember, you must still set the build action property on the link file in order for it to be recognised as a code analysis dictionary.
Note: You don't actually need to add the dictionary.xml file to the solution, but it obviously must be checked into your source control system and it should be referenced relatively, not absolutely.

The reason
In most projects I've seen, the code analysis rule CA1704 - Identifiers should be spelled correctly is all too easily ignored by adding a rule to the global suppression file. Personally, I don't like this because I think the global suppression file should not be used as a custom dictionary, especially when there is an alternative. The custom dictionary method is much more portable across projects and it preserves the separation of spelling against genuine code analysis errors.

Tuesday, 29 May 2007

Microsoft released Enterprise Libraries 3.1 - May 2007

Microsoft have release Enterprise Library 3.1 which contains a few updates from the previous January 06 version. I've installed it and I much prefer the cleaner start menu options which just take you to the source folder and let you browse away.
Note: If you already have the Enterprise Library 3.0 installed, you must uninstall it before installing the Enterprise Library 3.1. However, you can install the Enterprise Library 3.0 or the Enterprise Library 3.1 when 2.0 is already installed.

The patterns & practices Enterprise Library is a library of application blocks designed to assist developers with common enterprise development challenges. Application blocks are a type of guidance, provided as source code that can be used "as is," extended, or modified by developers to use on enterprise development projects. This release of Enterprise Library includes application blocks for Caching, Cryptography, Data Access, Exception Handling, Logging, Policy Injection, Security and Validation.

Monday, 21 May 2007

Generic collection classes allow nulls

Something to bear in mind when using generic collections in .NET is that they allow you to add null into the collection for reference types. This is not a bug but it means that you need to be careful when iterating through the collection.

For example, if you had a collection declared as
Collection<Customer> customers = new Collection<Customer>();

then add a null into the collection like so:
customers.Add(null);

it adds a null reference into the collection. This means that customers.count returns 1 and all looks well, but this is not so good if you try to iterate around the collection like this:

foreach(Customer customer in customers)
{
customer.Firstname = "test";
}

You would get a null reference exception as the customer object in this case is null. This means you have to clutter your code with null checks as you iterate through the collection. Wouldn't it be nice if the .NET framework provided non-nullable generics collection classes? It's on my list to create a class that enables this. Watch this space.... :)