Self Documenting Code - FAIL

I read some code the other day that made me do a double take.

    if(businessObject.Id.Equals(new Guid()))
    {
        // create object in db
    }

The first thing I thought was "Is this even possible? Will this code ever run?" But it will, and it does, because the default constructor on a Guid returns Guid.Empty. And while this is counter intuitive, it is the expected behavior of a default constructor on a value type.

The C# spec says that a default constructor is implicitly provided and cannot be overridden. And the behavior is to give a value produced by a bit pattern of all zeros. So this isn't a problem with the behavior of Guid, it's a problem with the behavior of the developer. Comparing to Guid.Empty is much more intuitive in terms of expected behavior.

    if (businessObject.Id.Equals(Guid.Empty))
    {
        // create object in db
    }

Please think about the poor souls who have to read your code after you are done creating it.

   
Comments
This is a very interesting story, but I bet you're projecting a bit. I seriously doubt that whoever wrote that was trying to be cute. It just reads like Cargo Cult programming to me, and I know a thing or two about reading, and yes, sometimes even writing, Cargo Cult code.

I would wager that businessObject.Id gets initialized to "new Guid()" in a commonly-used code path (looks like this might be the way they were testing that the object has never been saved?), and the programmer checked it out in the debugger and found out that the result was always the same when "new Guid()" is called, and never bothered to figure out that that value was Guid.Empty. He may even have scratched his head for a second and wondered why "new Guid()" doesn't actually give him a new GUID, but then said "screw it, this works", and he got back to work planting SQL injection vulnerabilities all over the code.

Also, I can still see 14 full words in the comment textarea. Could you make the font a little bigger?
Add Your Comment
Your email address will never be displayed anywhere.
Name:
Email:
Website:
Comment:
Type the word 'banana':
Blog Home
Recent Posts
Clearing the ClickOnce App Cache
VB.NET Gotchas for C# Devs
Dreamhost 1 year Special
Can I Suggest Bit Torrent?
Moq and VB.Net are Frenemies
Google Buzz - Impressions
O Rly? Intellisense requires XML + DLL
Self Documenting Code - FAIL
The 'F' in TFS is for 'Friction'
NDC 2009 Videos
Skills Test - FAIL!