Ikea Bekant

The idea is very old and it’s very likely there are other manufacturers, maybe with better implementations of it. But it’s notable and I hope I’ll be able to buy these desks for my entire team.

Dangerous multithreaded code

We’ve had some customers report issues with our product. Not all of them report the issue, and, although the symptoms are the same, the real issue may be different at each customer site.

While troubleshooting, I’ve stumbled upon the following code sequence (the names are meaningless, I’ve changed them as I’m not allowed to publish our source code).

public class Manager
{
/// ...
private readonly object _threadlock = new object();
private static State _fieldA;
/// ...
internal void Init()
{
    if( _fieldA != StateNotInitialized )
    {
        return;
    }
    
    lock( _threadlock )
    {
        _fieldA = RestoreFromDisk();
       /// ...
    }
}
}

I didn’t see anything wrong at the beginning. While discussing with a coworker, I’ve realized the code is prone to race condition. A more experienced coworker pointed out that the standard implementation pattern here should be the “double check locking” and also the _threadlock field should be static.
The updated code sequence is:

public class Manager
{
/// ...
/// MAKE THIS FIELD STATIC, TO REALLY LOCK ON IT!
private static readonly object _threadlock = new object();
private static State _fieldA;
/// ...
internal void Init()
{
    // Check once, to avoid the costly lock acquiring operation if it is not needed.
    if( _fieldA != StateNotInitialized )
    {
        return;
    }
    
    lock( _threadlock )
    {
        // Check again, some other thread may have already initialized the field.
        if( _fieldA != StateNotInitialized )
        {
           return;
        }
        _fieldA = RestoreFromDisk();
       /// ...
    }
}
}

Young developer code

A code sequence I’ve found while analyzing some ASP.NET legacy code.

        var isAlpha = string.Empty;
        try { isAlpha = Convert.ToString(Request.QueryString["isAlpha"]); } catch{}

The normal code sequence should be

        var isAlpha = Request.QueryString["isAlpha"] ?? string.Empty;

Writting settings in json

We’ve used to write our settings in xml files. All good, until you want to store the xml files in resources ( to ensure the final user does not mess with the settings, for example).
One of my coworkers suggested a few years ago that we use Json files in such situations; we tried this, and we’ve been doing it ever since.
There are many advantages for our development process, but there are two important disadvantages:
– there’s no schema validation
– one cannot insert comments.
These disadvantages are mitigated at this moment by using specific libraries.
There’s one alternative: HJSON (Human Readable JSON).
See http://laktak.github.io/hjson/.