woensdag 31 augustus 2011

Singleton in C#

One of the most used design patterns is the singleton pattern. There are a lot of implementations in each language. Thanks to Jon Skeet, I could find the best implementations for C#.

I prefer this lazy and threadsafe implementation for all my pre .NET 4 applications:



The .NET 3's lambda expression and .NET 4's generic Lazy class can create a lazy and threadsafe implementation without subclass:

woensdag 24 augustus 2011

The right way to get an auto-incremental id

When you write a PostgreSQL-appliction, you often need to fetch the id of inserted rows. In the past years, I've used the following three appoaches.

The person table is used as an example and has an auto-incremental primary key:

A sequence will automatically be created for the person_id column.

Now we want to insert a person and get his person_id:

The person will be inserted and you get his person_id. But only as long as you are the only user inserting in the person table. When there are concurrent inserts, the chance is high to get a wrong id with this method.

The next method is a little better:

This approach uses a transaction and the lastval() function. The generated id will be stored in a transactionvariable and is concurrent proof.

I recently added a lot of triggers to my database and suddenly I was getting invalid id's with the lastval() function. This happens only if a sequence is incremented in the trigger.

The last transactionless approach is concurrent- and triggerproof. This is the best Method: