Aug 20

The singleton pattern belongs to the creational patterns and is widely used in one form or another.

Use Cases

If you need to access an object throughout the application, like settings, the singleton pattern could be considered.

If you have objects that are very expensive to create but are state less (it doesn’t matter if you use instance a, instance b or instance c), the singleton pattern can improve the performance.

How does it work

The singleton pattern limits the number of instances of a given type, usually, the number is limited to just one.

The classical singleton pattern forbids direct instantiation of the object. Instead, you have to call a static method to get the current instance.

Example (in C#)

public sealed class Settings
{
    private static readonly Settings _instance = new Settings();
    static Settings() { }
    private Settings() { }

    public static Settings Instance
    {
        get { return _instance; }
    }
}

Another Method

Many IoC-container have some kind of lifecycle and most of them have a lifecycle called singleton or similar.

Whenever the container is asked for a type with it’s lifecycle set to singleton, the container will try to find an existing instance of the requested type.

If no such instance exists, the container will create one and save it for all further requests.

If the type exists, the container will simply return the existing instance.

Drawbacks

Without an IoC container, you rely on the implementation of the singleton in regards to unit testing.

A singleton is basically nothing more than a global variable. Therefore, all negative aspects of global variables apply to a singleton.

Tagged with:
Aug 19

The facade pattern belongs to the structural design patterns and is used rather often.

Use cases

If you have a bunch of low level services and want to consume them together in the UI, the facade pattern can help with that.

If you have to talk to an ugly legacy application, the facade pattern can be used to built an anti corruption layer.

If the underlying services take many arguments but your applications only uses very few of them and uses default values for the rest, the facade pattern can be used to hide those useless arguments. Doing so can lead to simpler and more readable calling code.

How does it work?

The mechanic behind the facade pattern is very easy to understand.

Imagine you want to display customers and their orders, the data access might be splitted up into a customerDAO and a orderDAO.

Without the facade pattern, you’d have to call the customerDAO for all customers and afterwards the orderDAO to receive all orders for each customer.

The facade pattern would simply hide those two calls and make them internally, exposing just a single method GetCustomersWithOrders().

facadepattern uml

Example (in C#)

First, the very basic DAOs:

public class CustomerDAO
{
    public Customer[] GetAllCustomers()
    {
        // Db Access...
    }
}

public class OrderDAO
{
    public Order[] GetOrdersWithCustomerIn(
        params Guid[] customerIds)
    {
        // Db Access...
    }
}

The UI that consumes those two DAOs:

public class ClientWithoutFacade
{
    public void DisplayCustomersWithOrders()
    {
        var customers = new CustomerDAO()
            .GetAllCustomers();

        var orders = new OrderDAO()
            .GetOrdersWithCustomers(
                customers.Select(x => x.Id).ToArray()
             );

        var custWithOrders = new List<CustomerWithOrders>();

        foreach (var customer in customers)
        {
            var cwo = new CustomerWithOrders(customer);
            cwo.AddOrders(orders
                .Where(x => x.CustomerId == cwo.Id));
            custWithOrders.Add(cwo);
        }

        // Fancy UI binding....
    }
}

Now, the facade and the new UI client

public class Facade
{
    public CustomerWithOrder[] GetCustomersWithOrders()
    {
        var customers = new CustomerDAO()
            .GetAllCustomers();

        var orders = new OrderDAO()
            .GetOrdersWithCustomers(
                customers.Select(x => x.Id).ToArray()
             );

        var custWithOrders = new List<CustomerWithOrders>();

        foreach (var customer in customers)
        {
            var cwo = new CustomerWithOrders(customer);
            cwo.AddOrders(orders
                .Where(x => x.CustomerId == cwo.Id));
            custWithOrders.Add(cwo);
        }

        return custWithOrders.ToArray();
    }
}

public class ClientWithFacade
{
    public void DisplayCustomersWithOrders()
    {
        var customers = new Facade().GetCustomersWithOrders();
        // Fancy UI binding....
    }
}
Tagged with:
Aug 12

I made a very basic solution for those who have trouble to get NHibernate up and running with unit tests.

  • Configuration is done via xml.
  • LinFu is used as proxy factory.
  • MbUnit / Galio is used for testing, dlls are included.
  • NHibernate 2.1 and all the required files are included.
  • SQLite is included for both, 32bit 64bit.

For those who have a 64bit os, as long as you use the ReSharpers test runner, everything should work fine. If you want to use another test runner, Icarus for example, you’d have to reference System.Data.SQLite.DLL from lib/sqlite64.

If there is anything wrong, please leave a comment.

The archive is available here.

Tagged with:
Aug 10

Since C# 3.0 it’s possible to write extension methods, these are very useful if you want to extend existing classes but don’t have access to them or if you simply want to add some convenience methods. The latter is what I did here.

If you want to know more about extension methods, you should take a look at this

Action Extensions

I really like the generic Action, Action<T> but i don’t to check for null every single time I want to fire them:

public static class ActionExtensions
{
    public static void Fire(this Action action)
    {
        if (action != null)
        {
            action();
        }
    }

    public static void Fire<T>(this Action<T> action, T arg)
    {
        if (action != null)
        {
            action(arg);
        }
    }

    public static void Fire<T, T2>(this Action<T, T2> action,
        T arg1, T2 arg2)
    {
        if (action != null)
        {
            action(arg1, arg2);
        }
    }
}

The same can be done with Func<T, TResult>:

public static TResult Fire<TResult>(this Func<TResult> func)
{
    return func != null ? func() : default(TResult);
}

public static TResult Fire<TResult, T>(this Func<T, TResult> func, T arg)
{
    return func != null ? func(arg) : default(TResult);
}

DataRow/ IDataRecord Extensions

If you have to work with IDataReaders or DataRows, chances are high that some of your code looks like this:

public void DoSomething(DataTable table)
{
    foreach (DataRow row in table.Rows)
    {
        var customer = new Customer
        {
            Id = (Guid)row["Id"],
            FirstName = row["FirstName"] == DBNull.Value
                                      ? string.Empty
                                      : (string)row["FirstName"],
            CompanyName = row["CompanyName"] == DBNull.Value
                                      ? null
                                      : (string)row["CompanyName"]
        };
    }
}

public void DoOtherThings(Customer customer, DataRow row)
{
    row["Id"] = customer.Id;
    row["FirstName"] = customer.FirstName == null
                                    ? string.Empty
                                    : customer.FirstName;
    row["CompanyName"] = customer.CompanyName == null
                        || customer.CompanyName == string.Empty
                                    ? DBNull.Value
                                    : customer.CompanyName;
}

These extension methods will reduce the code duplication and make it a little more readable:

public static class DataRecordExtensions
{
    public static T GetValue<T>(this IDataRecord dataRecord, string column)
    {
        return GetValue<T>(dataRecord, column, true);
    }

    public static T GetValue<T>(this IDataRecord dataRecord, string column,
                                              bool nullString)
    {
        var value = dataRecord[column];

        if (value == DBNull.Value)
        {
            if (typeof(T) == typeof(string))
            {
                if (!nullString)
                {
                    return (T) (object) string.Empty;
                }
            }

            return default(T);
        }

        return (T)value;
    }

    public static T GetValue<T>(this DataRow row, string column)
    {
        return GetValue<T>(row, column, true);
    }

    public static T GetValue<T>(this DataRow row, string column,
                                              bool nullString)
    {
        var value = row[column];

        if (value == DBNull.Value)
        {
            if (typeof(T) == typeof(string))
            {
                if (!nullString)
                {
                    return (T)(object)string.Empty;
                }
            }

            return default(T);
        }

        return (T)value;
    }

    public static void SetValue<T>(this DataRow row, T value,
                                                 string column)
    {
        SetValue(row, value, column, false);
    }

    public static void SetValue<T>(this DataRow row, T value,
       string column, bool defaultDbNull)
    {
        object val = value;

        if (defaultDbNull)
        {
            if (ReferenceEquals(value, default(T)))
            {
                val = DBNull.Value;
            }
            else if (typeof(T) == typeof(string))
            {
                if ((string)(object)value == string.Empty)
                {
                    val = DBNull.Value;
                }
            }
        }
        else if(val == null)
        {
            if (typeof(T) == typeof(string))
            {
                val = string.Empty;
            }
            else
            {
                val = DBNull.Value;
            }
        }

        row[column] = val;
    }
}

The code above could now be written as:

public void DoSomeThing(DataTable table)
{
    foreach (DataRow row in table.Rows)
    {
        var customer = new Customer
        {
            Id = row.GetValue<Guid>("Id"),
            FirstName = row.GetValue<string>("FirstName"),
            CompanyName = row.GetValue<string>("CompanyName", true)
        };
    }
}

public void DoOtherThings(Customer customer, DataRow row)
{
    row.SetValue(customer.Id, "Id");
    row.SetValue(customer.FirstName, "FirstName");
    row.SetValue(customer.CompanyName, "CompanyName", true);
}
Tagged with:
Aug 05

Today a new trainee was assigned to me. He just completed his in-firm training in another company and applied for a job.

In order to find out what he knows, I thought it would be a good idea to go through the code of some tools.

We began with a tool that prints invoices. It has two Forms and no architecture at all. Although the code was a mess, he could easily tell how it worked.

After that, we looked at a tool that queried some data, applied some validation to it and if necessary corrected it. This tool used the command pattern for validation / correction and loaded those commands via reflection (about 50 in total). It was way harder for him to tell what was going on. He asked why anyone would do things this complicated and suggested to use a switch block instead.

The third tool was a little more complicated, the UI used the passive view pattern, persistence was dealt with by NHibernate, StructureMap wired it all up and a test suite covered most parts. I wrote it some time ago but could still easily navigate through it as it was well structured but he was totally overwhelmed and unable to say anything other than “it is too complicated”.

Using these good practices has advantages but these advantages are not free.

There are way more developers like my trainee that never heard about good practices and the like than those who heard about these practices let alone applying them. These developers usually just want to get the job done and mostly they do so, on time.

If you work in a very small IT department that only deals with in house stuff, should you use patterns, unit testing and other good practices or should you just do it “the good old way”?

If you do it “the good old way” maintenance costs increase, time to bug fix / feature are less predictable yet everyone should be able work with it.

If you use good practices, maintaining your applications either can’t be done by every “developer from the street” or requires high upfront learning effort. On the other side, after this initial learning phase is over, the maintenance costs should decrease and time to bug fix / feature should be more predictable.

Tagged with:
Aug 03

Note: I’m talking about MS SQL Server 2005/8, it may or may not apply to other dbs.

Security:

You can set rights on the procedure level.

Yes, but you can also set the rights on view / table level.

Stored procedures are always immune to sql injection. 
Ad hoc queries are always vulnerable to sql injection.

Wrong.

Stored procedures that take strings as parameters and execute them as sql are open to sql injection.

Parameterized ad hoc queries prevent sql injection.

Performance / Execution Plan:

The execution plans for stored procedures are cached whereas ad hoc queries generate new plans each time they are executed.

Wrong.

If there is an execution plan that fits the query, it will  be used. The db doesn’t care if the query was an ad hoc query or a stored procedure.

Stored procedures are not pre compiled, they are compiled at runtime, just like any other query.

There is one thing to note though, if you change a parameter (not the value but for example nvarchar(9) instead of nvarchar(22)) a new plan will be generated.

Source: MSDN1, MSDN2, MSDN3, Blog

Centralization:

With stored procedures you “have it all in one place”

Wrong.

You don’t have it one place, it’s in your application as calling code and in your db as stored procedure. If the procedure changes and requires different parameters the calling code has to change too.

You can reuse stored procedures and only have to optimize them once

While that is true, you have to see the other side too. If multiple applications use a stored procedure you can’t easily change the procedure. You’d have to make sure that you didn’t break any of the other applications.

Optional Parameters:

If you use stored procedures for updates, you have to choose between efficient queries and maintenance.

If you want to go with efficient queries, you’d have to create stored procedures for every use case that changes something. If you have a customer table, the procedures might be ChangeCustomerAddress, ChangeCustomerBillingAddress, ChangeCustomerName etc.

If you favor easier maintenance, you’d just have one big update procedure that takes all values at once.

With Ad Hoc Queries you can have both. It’s easier to maintain and more efficient if you have a single method that builds a query that excludes all unnecessary columns.

Changes:

You can change a stored procedure without redeploying the application

That is partially true.

If you really have to change a query, you’ll likely have to change the application too.

Tuning is another story, you can tune a stored procedure without touching the application. On the other hand, you could also tune the query in isolation and change the query when the application has to be recompiled for other reasons.

Tagged with:
preload preload preload