Thursday, September 27, 2007

Lazy Initialization Complacency Syndrome

I and a friend of mine were debugging her code for a problem and I couldn't crack it at first. She later debugged it and asked me to crack it and when I did, I was kicking myself. Decided to blog it for others' benefit :)

The code snippet is something like below:


public void addToMap(Object key, Object value)
{
    if(member_map == null)
    {
        member_map = new HashMap<Object, Object> ();
    }
    else
    {
        member_map.put(key, value);
    }
}


It simply lazy-initializes a map that is a class member variable and adds the key-value pair to the map. We tested it with 2 records fetched from a database table and tried to print the contents. We expected two records, but only the last record was stored onto the map and this kept us guessing for a long time.

The problem here is in the if-else part. For the first record, the map is null and it gets lazy-initialized. And the 'put' call was in the else loop, so the first record never got stored!


Three lessons

1. Do not else-ify lazy-initialization: When you lazy-initialize, put the null check in if condition, but do not add an else to it. The code should have been:


public void addToMap(Object key, Object value)
{
    if(member_map == null)
    {
        member_map = new HashMap<Object, Object> ();
    }
    // No "else"
    member_map.put(key, value);
}

2. The importance of quantitative and qualitative test data: What we did was a typical case of testing with insufficient data. We shouldn't have tested only with two records, we should have tested with more numbers. That way, the problem would have been obvious.

3. Thinking out-of-box: We couldn't crack it coz d problem was in the perception with which we thought about it. It wasn't that only the last record was stored, rather it was that the first record was NOT stored.

And I thought I could wash away the sin of not cracking it only by spreading the lesson, hence the blog :)

3 Comments:

Blogger Sudhir said...

this is good man.
I could not get whats the issue when I saw it the first time.

9:24 PM  
Blogger Premma said...

Nice..its usefull dude!

1:28 AM  
Blogger seyal said...

code'un sariyilla, review'un pannala !?

2:38 AM  

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home