The World According to Nick
Politics, News, Photography, and Triathlons... What don't I talk about?
Friday, April 16, 2004
<< Why Gmail Will Fail What If Bush Had Said This? >>
My Syntactic Sweet Tooth
I haven't done a general programming rant in quite a while...so you'll have to forgive me for this one. I'm a fan of little syntax shortcuts in programming languages. You know what I mean, those little things that are assumed in code that a lot of people hate because "they make your code unreadable" or "less understandable". Of course I think that's B.S. It just means that you don't know the language as well as I do :D. Its like saying that saying "I'm" is less understandable than "I am". Unfortunately it seems like these gramatical perfectionists are winning out in C#. A lot of the nice syntactic sugar that I took for granted in C++ is gone in C#. Case in point... null object checking. In C++ you could write the following:

SomeObject* obj = FunctionThatReturnsSomeObject();
if ( obj )
   DoSomethingWithSomeObject( obj );

The syntactic sugar here is that an object can be referenced like a bool. If obj is null, then the if statement fails and DoSomethingWithSomeObject() never gets called, otherwise it does. However in C#, you can't do that. There is no implicit cast to bool in this case so you have to write this:

SomeObject obj = FunctionThatReturnsSomeObject();
if ( obj != null )
   DoSomethingWithSomeObject( obj );

You may say... what's the big deal? Wait... you would actually have to say... what is the big deal. Nothing... its syntactic sugar. But... when you have lots of objects that could possibly be null that you want to check for in order to avoid null reference exceptions, it's nice not to have to constantly, and explicitly say you're checking for null. Plus I think the code visually looks better, and it is generally understood what being accomplished there. And while I'm at it... what's with C#'s inconsistancy in bracing rules?

// Don't need to brace around a single statement if clause
if ( obj != null )
   DoSomethingWithSomeObject( obj );

// You do need braces around single statement try/catch/finally blocks
try
{
   DoSomethingWithSomeObject( obj );
}
catch ( Exception ex )
{
   MessageBox.Show( "obj is null!" );
}
finally
{
   if ( obj != null ) obj.Dispose();
}

Ok... that's enough for now.
# Posted at 9:05 AM by Nick  |  Comment Feed Link No Comments  |  No Trackbacks

 Add to del.icio.us |  Digg this Post | Filed Under: Old Blog

Comments are closed.


© Copyright 2012 Nick Schweitzer
Powered By newtelligence dasBlog 1.9.7067.0
Theme Based on Design By maystar