Static Issues

time to read 2 min | 349 words

The easiest way to get access to something, is to make is static. This way, you can to it from everywhere in the application, without having to instansiate it every place you need it.

Consider this piece of code, which saves an order to the database:

using(IDbCommand command = DataBase.Connection.CreateCommand())

{

    command.CommandText = "INSERT INTO Customers VALUES('New','Customer'";

    command.ExecuteNonQuery();

}

Here is how we define the DataBase class:

public class DataBase

{

    static IDbConection connection;

 

    public static IDbConnection Connection

    {

        get

        {

            if ( connection == null)

            {

                connection = CreateAndOpenConnection();

            }

            return connection;

        }

    }

}

Even ignoring the pitfall of leaving connections open for a long time, can you see the problem?

What happen if we are using this on the web, and two users are trying to view a page at the same time? One of them is likely to get the "data reader is already open" error. The same issue appear if you want to work multi threaded.

This is a major issue when using static, and it is usually the reason for ruling them out. By the way, I'm using static as the word here, but everything I say here can be said about Singleton as well.

I'll post later how to handle this issue safely on multi threaded (and web) scenarios while maintianing the ease of use that static gives us.