Contracting in the UK

Be sure to chcek it out!

Contracting in the UK

Roslyn – C# Compiler

I’m obviously very glad that the compiler has now been rewritten from scratch allowing
it to support many new features. Some I consider very handy and some I just don’t get (not in the sense that I don’t know what they do, but rather what benefit they bring to the .NET world) As a C# developer I will focus on C# features.

Null-Conditional Operator

One of the improvements, they say is the conditional check for null:
Whereas before you had to write something like this to check for null

public static string Truncate(string value, int length)
{
    string result = value;
    if (value != null) // Skip empty string check for elucidation
    {
        result = value.Substring(0, Math.Min(value.Length, length));
    }
    return result;
}


Now it's much shorter:

public static string Truncate(string value, int length)
{
    return value?.Substring(0, Math.Min(value.Length, length));
}

At first it seems like a very handy tool, but my worry is that this feature will be greatly abused. Some developers would be tempted to write this type of code:

public static string Truncate(string value, int length)
{
    return value?.Item1?.Item1?.Customer?.FirstName;
}

Obviously the alternative would be much bulkier, however this approach takes away from the developer the ability to throw a 'NullReferenceException'. Say we always expect the 'Customer' to be not null. If it's null it's a bug, so an exception has to be thrown. With the shorthand notation it's very easy to miss that.

However in this case it's quite handy although only a couple of lines of code are eliminated

OnTemperatureChanged?.Invoke(this, value)

Auto-Property Initialisers

I have mixed fillings about this. This generally allows you to create a auto-property with a 'get' accessor only while still being to supply a value:

public class FingerPrint
{
    public DateTime TimeStamp { get; } = DateTime.UtcNow;
}

"As the code shows, property initializers allow for assigning the property an initial value as part of the property declaration. The property can be read-only (only a getter) or read/write (both setter and getter). When it’s read-only, the underlying backing field is automatically declared with the read-only modifier. This ensures that it’s immutable following initialization."

When I first saw this I was unsure whether it would return current of 'DateTime.UtcNow' or the static value.

Nameof Expressions

This one I think is a very useful feature and gives you an ability to get the name of the parameter.

public void Foo(string message)
{
    if(string.IsNullOrWriteSpace(message))
    {
       throw new ArgumentException(nameof(message));
    }
}

This would also come in handy when implementing 'INotifyPropertyChanged' interface. Currently you either have to use expressions or '[CallerNameAttribute]'

Primary Constructors

This alloys you to write constructors in the following manner:

public struct Pair(T first, T second)
{
    public T First { get; } = first;
    public T Second { get; } = second;
}

The whole purpose is to eliminate code bloat and I think this is quite intuitive.

Expression Bodied Functions and Properties

public override string ToString() = string.Format("{0}, {1}", First, Second);

I can see its use. However some developers will be inclined to implement a more complex logic using this technique. So the rule should be that this is used for cases when the override is very simple. If you have to use

public override string ToString()
{
    //complex logic
}

In this case it makes more sense to do an override using the old fashioned way.

I'm glad that Microsoft decided not to go ahead with index properties, this was just another way of doing something that you could already do.

Using Static Methods

I like this feature. Quite often you have to work with a static class, for example Math and then you end up with Math.Min(..) * Math.Pow(..) etc. The new feature would eliminate having Math. , by importing the class like you would import a namespace:

using System.Math;
public static void Main(string [] args)
{
    var result = Min(x, 0.5) * Max(y, 1);
}

References:
http://msdn.microsoft.com/en-us/magazine/dn802602.aspx
https://roslyn.codeplex.com/

Today I will be presenting my ideas based on the analysis of the code issues I found while re-factoring. Some of the issues I have found are not too serious, but there are many areas where it could be done better (much better) So here are the notes:

* Solution has to build. It might seem obvious but the developers here don’t follow one of the most important rule. When checking in the code into the branch, especially if there is more than one person working on it, it has to build! So many times I come in in the morning and seeing that someone checked in the code that doesn’t compile and that in turns means that I cannot do much until that is fixed.
Rule #1 – the code you check in must compile, full stop!

* Tuples – I was never in favour of tuples, but they have their use, but that use should be constrained to internal implementation. Tuples should never be exposed in a public interface to prevent other developers working on the code guessing what Item1, Item2 …Itemn stand for.
Rule #2 – do not expose tuples in public interfaces, use a class or a struct, which ever one is more appropriate.

* Singletons and Static members – don’t use them. If you need a singleton like behavior do it using you preferred IoC container. There is a valid case for using static methods, if the method is stateless you should declare it as static, but that is different.
Rule #3 – Do not use static members and singletons.

* Separation of Concerns – don’t create classes that do ‘everything’, don’t create a facade to a database. Instead split the class into smaller chunks each responsible to do one thing and do it well. That simplifies development and lets you to trace what is being used and where. It quite often that you would then realise that not everything is used and some code can be removed.
Rule #4 – Split large classes into smaller ones.

* Exception Handling – always catch those exception that can be handled. There are valid reasons for catching all exceptions, however before doing that, put catch statements for exceptions that you can do something about. The generic catch statement then can just be used for logging
Rule #5 – Catch the most specific exceptions first and generic exceptions last.

* Dispose and Finally – You should always implement IDisposable if any of the fields are disposable. Think hard before implementing a finiliser. When objects with finilisers are instantiated they are placed into the finalisation queue. While it is fine when the application is single threaded it could create contention to finilisation queue when instatiating those objects from multiple thread. But if you doing that it is a definite sign that you’re doing something wrong.
Rule #6 – Implement IDisposable if any of the fields is IDisposable. Use finalisers with caution

While going through the codebase of the counterparty risk reporting system I came across thousands of cases where you can sense that the developer is afraid to write code that throws an exception.

The most primitive examples is returning true/false if the operation completed successfully, but this one is very easy to spot and therefore fix. The same applies to handling all exceptions.

But the one which doesn’t stand out very often is the usage of ‘as’ instead of plain casting or combination of ‘as’ and then a null check. Without a null check there is a possibility of spotting a bug at the early stages of testing, even though instead of ‘InvalidCastException’ you get a ‘NullReferenceException’. But with a null check in place the bug would go pretty much unnoticed. The question should then be – why a certain parameter, item in the array, should not be of the particular type? If there is a valid reason or are you just “scared”?

When browsing .NET source code you might come across an empty try clause and some code in the finally clause:

try
{
}
finally
{
// few lines of code here
}

The answer is to guarantee the execution of the code in case something calls Abort() on the thread. Since .NET 2.0 execution of the code in the finally statement is guaranteed even if something calls Abort() on the thread. In the earlier versions of.NET it was possible that the finally clause is never executed. I don’t expect to ever write anything that would leverage this, however it still nice to know.

This implementation improves the behaviour of the standard ObservableCollection when dealing with a large number of elements. This collection does not fire an event for each inserted element, but fires a reset event when adding elements

    public class RangeObservableCollection<T> : ObservableCollection<T>
    {
        private static readonly NotifyCollectionChangedEventArgs ResetChangedArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
        private static readonly PropertyChangedEventArgs CountChangedEventArgs = new PropertyChangedEventArgs("Count");
        private static readonly PropertyChangedEventArgs ItemChangedEventArgs = new PropertyChangedEventArgs("Item[]");
 
        public RangeObservableCollection(IEnumerable<T> items)
            : base(items)
        {
        }
 
        public RangeObservableCollection(List<T> list)
            : base(list)
        {
        }
 
        public RangeObservableCollection()
        {
        }
 
        public void RemoveRange(IEnumerable<T> list)
        {
            if (list == null) throw new ArgumentNullException("list");
 
            foreach (T item in list)
            {
                Items.Remove(item);
            }
 
            OnCollectionChanged(ResetChangedArgs);
            OnPropertyChanged(CountChangedEventArgs);
            OnPropertyChanged(ItemChangedEventArgs);
        }
 
        public void AddRange(IEnumerable<T> list)
        {
            if (list == null) throw new ArgumentNullException("list");
 
            foreach (T item in list)
            {
                Items.Add(item);
            }
            OnCollectionChanged(ResetChangedArgs);
            OnPropertyChanged(CountChangedEventArgs);
            OnPropertyChanged(ItemChangedEventArgs);
        }
 
        public void RemoveAll()
        {
            Items.Clear();
            OnCollectionChanged(ResetChangedArgs);
            OnPropertyChanged(CountChangedEventArgs);
            OnPropertyChanged(ItemChangedEventArgs);
        }
 
        public void ReplaceAll(IEnumerable<T> list)
        {
            if (list == null) throw new ArgumentNullException("list");
            Items.Clear();
            this.AddRange(list);
        }
    }

Always Create an Interface

Every class that defines operations must have an interface.  The interface should serve as a contract and is particularly useful when mocking the behaviour during unit testing. The interface will also be used for registration with the container.

public class MyService : <strong>IMyService</strong>
{
    public void ProcessBatch(DateTime reportingDate)
    {
        var processor = new BatchProcessor(reportingDate);
        processor.Process();
    }
}

public interface IMyService
{
    void ProcessBatch(DateTime reportingDate);
}

Avoid Instantiating Objects Directly

For example we have the following implementation

public class MyService
{
    public MyService()
    {
    }

    public void ProcessBatch(DateTime reportingDate)
    {
        var processor = <strong>new BatchProcessor(reportingDate);</strong>
        processor.Process();
    }
}

The above code cannot be unit tested in isolation, by testing MyService we inadvertently end up testing BatchProcessor as well. The code could be rewritten as:

public class MyService : IMyService
{
    private readonly IBatchProcessorFactory _batchProcessorFactory;
    public MyService(<strong>IBatchProcessorFactory</strong> <strong>batchProcessorFactory</strong>)
    {
        _batchProcessorFactory = batchProcessorFactory;
    }

    public void ProcessBatch(DateTime reportingDate)
    {
        var processor <strong>= _batchProcessorFactory.Create(reportingDate);</strong>
        processor.Process();
    }
}

public interface IBatchProcessorFactory
{
    void IBatchProcessor Create(DateTime reportingDate);
}

public class BatchProcessorFactory : IBatchProcessorFactory
{
    public IBatchProcessor Create(DateTime reportingDate)
    {
        return new BatchProcessor(reportingDate);
    }
}

Now, in order to test the logic of MyService, we can mock IBatchProcessor and just test that the Process method is called on the instance!

Avoid Passing Primitives in Constructor

public class MyService : IMyService
{
    private readonly string _connectionString;
    public MyService(<strong>string connectionString</strong>)
    {
        _connectionString = connectionString;
    }

    public void Save()
    {
        using(var connection = <strong>new SqlConnection(_connectionString))</strong>
        {
            // Do some work
        }
    }
}

We should change it to:

public class MyService : IMyService
{
    private readonly IConnectionStringProvider _connectionStringProvider;
    public MyService(<strong>IConnectionStringProvider connectionStringProvider</strong>)
    {
        _connectionFactory = connectionFactory;
    }

    public void Save()
    {
        using(var connection <strong>= new SqlConnection(_connectionStringProvider.GetConnectionString()))</strong>
        {
            // Do some work
        }
    }
}

* Alternatively we could use a Factory pattern to get a connection instance

Don’t Pass Container in the Constructor

public class MyService : IMyService
{
    private readonly ISqlConnectionFactory _connectionFactory;
    public MyService(<strong>IUnityContainer container</strong>)
    {
        _connectionFactory = <strong>container.Resolve<ISqlConnectionFactory>();</strong>
    }
}

Instead pass the interface into the constructor:

public class MyService : IMyService
{
    private readonly ISqlConnectionFactory _connectionFactory;
    public MyService(<strong>ISqlConnectionFactory connectionFactory</strong>)
    {
        _connectionFactory = connectionFactory;
    }
}

The IoC container will resolve the references automatically:

var container = new UnityContainer();
container.Register<ISqlConnectionFactory, SqlConnectionFactory>();
container.Register<IMyService, MyService>();
//…
var myService = container.Resolve<IMyService>();

Avoid Named Instances

public class RiskDbSqlConnectionFactory : ISqlConnectionFactory
{
}
public class StaticDataSqlConnectionFactory : ISqlConnectionFactory
{
}

container.Register<ISqlConnectionFactory, RiskDbSqlConnectionFactory>(“RiskDB”);
container.Register<ISqlConnectionFactory, StaticDataSqlConnectionFactory>(“StaticDB”);

Instead use different interfaces to differentiate:


public class RiskDbSqlConnectionFactory : ISqlConnectionFactory, IRiskDbSqlConnectionFactory
{
}

public class StaticDataSqlConnectionFactory : ISqlConnectionFactory, IStaticDataSqlConnectionFactory
{
}

container.Register<IRiskDbSqlConnectionFactory, RiskDbSqlConnectionFactory>();
container.Register<IStaticDataSqlConnectionFactory, StaticDataSqlConnectionFactory>();

Avoid Static References

public class MyService : IMyService
{
    public void DoSomething()
    {
        SaveData(<strong>DateTime.Now</strong>);
    }
}

If you have to use a static property or a method in the code write a wrapper. For example:

public interface IDateTimeProvider
{
     DateTime GetCurrentTime();
}

public class DatetimeProvider : IDateTimeProvider
{
    public DateTime GetCurrentTime()
    {
        return DateTime.Now;
    }
}

public class MyService : IMyService
{
    private readonly IDateTimeProvider _dateTimeProvider;
    public MyService(IDateTimeProvider dateTimeProvider)
    {
        _dateTimeProvider = dateTimeProvider;
    }

    public void DoSomething()
    {
        SaveData(_dateTimeProvider.GetCurrentTime());
    }
}

This technique gives you an opportunity to mock DateTime to any value during unit testing

Interface Segregation (Liskov Principle)

Consider splitting large interfaces into smaller ones

public class Repository : IRepository
{
    public Item Load()
    {
    }

    public void Update(Item item)
    {
    }
}

This could be converted to 2 interfaces IItemLoader and IItemUpdater . The class definition would look like this:

public class Repository : IRepository, IItemLoader, IItemUpdater

Lifetime Management

If you need to make sure there is only going to be one instance of a particular type you have to register you class with ContainerControlledLifetimeManager instance.

container.Register<IMyService, MyService>(new ContainerControlledLifetimeManager())

Then the resolve method would return 1 instance of the class. If nothing is specified then a new instance will be created each time.

If you need to register an already existing instance then do the following:

var myService = new MyService();
container.RegisterInstance(typeof(IMyService), myService, new ContainerControlledLifetimeManager());

This example demonstrates how to create a singleton without doing any synchronisation

public class LockingExample
{
    public static StringBuilder Resource
    {
        get { return InnerResourceContainer.Resource; }
    }

    private static class InnerResourceContainer
    {
        public static readonly StringBuilder Resource = new StringBuilder();
    }
}

First post

word pressThe thought of starting a blog has been with me for a while now, since these days
everyone has a blog. I do realise that nobody is probably going to read it, so it will be more of a diary for myself