Thursday, February 22, 2007

Don't do objects - do types!

I've been faithless the last couple of months, doing lot's of code in C# for ASP.NET instead of using a real programming language, i.e. C++. Actually, C# is pretty nice and ASP.NET is a very productive environment for Web Application programming.

During this time I've come across a usage pattern that I really want to discourage. C# is a beautifully typed language, especially with the introduction of Generics (not to be confused with Templates in C++, they are two very different things) - so why do so many people insist on stuffing things into strings and objects?

A typical example is the Guid structure in C#. It's essentially byte-array holding the 16 bytes of a GUID, a Globally Unique Identifier. Very useful, and very common. But very frequently stored and passed as a string, or even worse, as an object.

I use a code policy that states that an object that has a specific type should always be stored, referenced and passed as that type. Even if it does come into the code in the form of a string, you should still convert it at the first opportunity and then keep it in it's natural typed form.

The rationale for this is that you can get some very nasty and hard-to-find runtime bugs with late effects, causing errors, instability and exceptions long after the initial problem occurred. Consider for example a Guid entering the system as a string, being stored as a string and then used. It might not be in the correct format, but that will not be discovered until way too late. If you follow a code policy to convert it into the appropriate type from the start, you'll automatically catch such things very early.

Work is also progressing on Xecrets, the safety-deposit box on the net that will launch in the summer time frame. I've given notice to my "day job", and will start working full-time on AxCrypt, AxCrypt2Go and Xecrets in June.

No comments:

Post a Comment