6 more things C# developers should (not) do

6 more things C# developers should (not) do

What C# developers should not do
For all wondering what are the things a C# developer should and should not do. As the continuation of my previous post 8 Most common mistakes C# developers make I decided to write another article about the things C# developers should always be aware of.

1. Try to avoid using the “ref” and “out” keywords.

There is rarely a situation that you really have to use “ref” or “out” keywords. It should be avoided as much as possible, because when you use them it means that your method probably tries to do too much (and therefore breaks the Single Responsibility Principle). It can also make your method less readable. To accomplish the goal of not using ref/out keywords it is usually enough to create a class that will represent multiple return values and then return an instance of this class as a result of the method. There are obviously situations when the usage of ref/out cannot be avoided like when using TryParse method, but these should be treated as exceptions to the rule.

2. Do not use OrderBy before Where

The above statement might sound very obvious but anyway some developers tend to forget about this. Let’s take a look at the following code:

var allCitiesInPoland =
    allCitiesInTheWorld.OrderBy(x => x.Name)
                       .Where(x => x.Country == Country.Poland);
In this hypothetical scenario firstly the collection of all cities in the world (according to some statistics: 2,469,501) will be sorted and then only these from Poland (897) will be returned. The result will be appropriate, the only problem is that it will be simply inefficient. Using the following code:

var allCitiesInPoland =
    allCitiesInTheWorld.Where(x => x.Country == Country.Poland)
                       .OrderBy(x => x.Name);
First of all we will choose only the cities from Poland and then order this significantly smaller collection alphabetically by name.

3. Always use Properties instead of public variables

When using getters and setters you can restrict the user directly from accessing the member variables. Secondly, you can explicitly restrict setting the values. Thanks to this you make your data protected from accidental changes. What is more, when using properties,  it is much easier to validate your data.

4. Take advantage of string.IsNullOrEmpty() and string.IsNullOrWhiteSpace()

Instead of:

if (name != null && name != string.Empty)
{
    [...]
}
It’s better to use:

if (string.IsNullOrEmpty(name))
{
    [...]
}
Sometimes we want to make sure that a string is not only not empty and not null, but also does not comprise of whitespaces. In such situation we could of course use the following code:
1
if (string.IsNullOrEmpty(name.Trim()))
{
    [...]
}
But why not using something that is already provided by the .NET framework (in version 4.0 and higher):

if (string.IsNullOrWhiteSpace(name))
{
    [...]
}
The example above can be treated as a more general principle. You should simply always try to find out whether something that you implemented is not already existing as a ready method in the framework that you use. Make sure that you went through all the methods in such .Net classes as e.g. String or IO.Path. This might potentially save you some time that you could have spent on reinventing the wheel.

5. Understand the difference between First() and Single()

Always remember that First() returns the very first item of the sequence, if no item exists it throws InvalidOperationException, whereas Single() Returns the only item in the sequence, if no item exists it throws InvalidOperationException,and if more than one item exists, it also throws InvalidOperationException.

6. Do not blindly use List

There are some cases when the usage of List is simply not recommended from performance point of view. You should be aware of the existence of e.g. HashSet or SortedSet which can considerably improve the performance, especially in case of large sets of items. To make you aware of how big the difference in performance between these two is, let’s consider the following piece of code:

class Program
{
    static void Main(string[] args)
    {
        const int COUNT = 100000;
        HashSet<int> hashSetOfInts = new HashSet<int>();
        Stopwatch stopWatch = new Stopwatch();
        for (int i = 0; i < COUNT; i++)
        {
            hashSetOfInts.Add(i);
        }
 
        stopWatch.Start();
        for (int i = 0; i < COUNT; i++)
        {
            hashSetOfInts.Contains(i);
        }
        stopWatch.Stop();
 
        Console.WriteLine(stopWatch.Elapsed);
 
        stopWatch.Reset();
        List<int> listOfInts = new List<int>();
        for (int i = 0; i < COUNT; i++)
        {
            listOfInts.Add(i);
        }
 
        stopWatch.Start();
        for (int i = 0; i < COUNT; i++)
        {
            listOfInts.Contains(i);
        }
        stopWatch.Stop();
 
        Console.WriteLine(stopWatch.Elapsed);
        Console.Read();
    }
}
After executing it you will see the difference:
100000 ‘Contains’ operations using HashSet: 0.002 sec
100000 ‘Contains’ operations using List: 28.74 sec

Of course HashSets or SortedSets are not golden means for every possible scenario. HashSet should be used in case when you care about the performance (especially if you know that you will operate on a large set of items) but do not care about the order. SortedSet is a bit slower than HashSet but will give you a sorted collection and is much faster than List.
Use List when you want to iterate through the collection. Iterating through all the items in a List it is generally much faster than through a set (unless you use inside such methods as Contains).
Previous
Next Post »