Reshef’s tip of the day

.net development tips

Archive for January, 2008

Implicit construction of objects

Thursday, January 3rd, 2008

An hidden and not commonly used feature of C# is the implicit constructor. It is so uncommon to see it, that one time (in band camp), when I saw it being used, it took me a while to understand what is going on…

Actually, implicit construction is not a real feature by itself, but rather a by-product of implicit conversion between datatypes. Look here for more information about implicit conversions.

Anyway, what it means, is that the object is being constructed by an invisible factory method.

Take a look at this options to instantiate an object:

Telephone tel = new Telephone("972542221234"); // By Ctor

Telephone tel = Telephone.New("972542221234"); // Factory method

Telephone tel = "972542221234"; // Implicit Ctor

Here is the implementation of the telephone object I used for this example. The implicit constructor implementation is bolded:

public class Telephone
{
    private readonly int countryCode;
    private readonly int areaCode;
    private readonly long phoneNumber;

    public Telephone(string phoneNumber)
    {
        // Dummy logic just for this example
        this.countryCode =
            Convert.ToInt32(phoneNumber.Substring(0, 3));

        this.areaCode =
            Convert.ToInt32(phoneNumber.Substring(3, 2));

        this.phoneNumber =
            Convert.ToInt64(phoneNumber.Substring(5));
    }

    public int CountryCode
    {
        get { return countryCode; }
    }

    public int AreaCode
    {
        get { return areaCode; }
    }

    public long PhoneNumber
    {
        get { return phoneNumber; }
    }

    public static Telephone New(string phoneNumber)
    {
        return new Telephone(phoneNumber);
    }

    public static implicit operator Telephone(string phoneNumber)
    {
        return Telephone.New(phoneNumber);
    }
}

This kind of syntax can help having less verbose code, and in software, less is usually more.

Throw meaningful exceptions!

Thursday, January 3rd, 2008

When you check for erroneous usage in the code you write, and there is a pretty good chance that this error was caused by a certain action (or more possibly the lack of an action), don’t just throw a meaningless exception that will leave the user of your code glancing helpless at the screen; give a guiding message that will help understand what he didn’t do correctly. Take a look at great example.

More helpful advices about exception handling are , and this article is a MUST READ in my opinion.

Jajah is the VoIP player that brought you web-activated telephony.