Reshef’s tip of the day

.net development tips

Implicit construction of objects

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!

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.

DynamicMethod full example

December 18th, 2007

My last post described how to generate a dynamic method for object instantiation that its type is not known at compilation time.

I felt that the code snippets in that post were too technical and it was hard to understand how and when to use it in the real world. Therefore I created a small sample application that shows how and when it can be used.

The application is a small rule engine that gets a rule definitions file about a user’s credit, parses the rules, generates C# code and compiles the code on runtime. The rule engine is then instantiated by using a dynamic method.

The file UserCreditRules.rules contains the definitions of the rules and the dynamic method is generated in the file RulesFactory.cs by the method GenerateFactoryMethod(…).

The sample application is here.

Reflection and performance: DynamicMethod

December 17th, 2007

Reflection has a performance price, however, there are times that it just can’t be avoided, like when creating a new instance of a type generated and compiled at runtime. Since the type does not exist when compiling the code, it can’t be referenced and therefore can’t be instantiated by:

BaseType instance = new GeneratedType();

where BaseType is the a type that GeneratedType inherits from.

So how to instantiate?

After generating the assembly, we have a reference to that assembly. The most naive and simple way is to call:

BaseType instance = (BaseType)generatedAssembly.
    CreateInstance("GeneratedType");

But unfortunately this is also the worst way performance-wise, since on runtime first it looks for the name of the generated type through all the types in the assembly, then it looks for the appropriate constructor and then it instantiates the object. It can be optimized by caching the ConstructorInfo of the  type and then calling it, which highly optimizes the instantiation time. There are other ways to achieve this goal but I am not going to go into it. For a thorough article and analysis take a look here (the source code is here).

In order to get the best performance, we can use the DynamicMethod class which generates IL code at runtime and creates a method out of it. This is done like this:

Type generatedType = CompilerSimulator.Compile().
    GetType("generated type name");

DynamicMethod dm =
    new DynamicMethod("GeneratedCtor", generatedType,
        Type.EmptyTypes, typeof(ContainingType).Module, true);

ILGenerator ilgen = dm.GetILGenerator();
ilgen.Emit(OpCodes.Nop);
ilgen.Emit(OpCodes.Newobj,
    generatedType.GetConstructor(Type.EmptyTypes));
ilgen.Emit(OpCodes.Ret);

GeneratedTypeFactoryMethod factoryMethod =
    (GeneratedTypeFactoryMethod)dm.CreateDelegate(
    typeof(GeneratedTypeFactoryMethod));

The GeneratedTypeFactoryMethod is a delegate:

delegate BaseType GeneratedTypeFactoryMethod();

Now, our code can return the generated method as delegate that will be called to to create a new instance of the generated type. By tests that I did I got results similar to direct instantiation (after setting up the factory delegate - but this happens only once).

Since writing IL code is not much fun, you can use a project named RunSharp that wraps IL emitting with a high-level interface.

Null object pattern

December 10th, 2007

There is a lot written about the null object pattern in the web, but it took me quite some time to find an example that I could relate to for null object.

Take a scenario where we have a email application with a message class:

public class Message
{
    private string m_recipient;
    private MailAccount m_account;

    public string Recipient
    {
        get { return m_recipient; }
        set { m_recipient = value; }
    }

    public MailAccount Account
    {
        get { return m_account; }
        set { m_account = value; }
    }
}

Lets say that we would like to view the massage pane window (pretty common requirement for a mail client), we will have to test the the Recipient and Account member for null value before accessing them.

Side effects when testing for null values is that we add code to the presentation logic which can possibly look like that:

void ShowMessage(Message m)
{
    string recipientDisplay = m.Recipient ?? String.Empty;

    string accountDisplay = m.Account ?? "NotSet";
    if(m.Account == null)
    {
        accountDisplay = "NotSet";
    }
    else
    {
        accountDisplay = m.Account.Name;
    }
    txtRecipient = recipientDisplay;
    txtAccountName = accountDisplay;
}

This is a lot of code just for displaying two fields. We should also remember that a developer can possibly forget to test for null values and therefore to get a null reference exception.

The null object attempts to help here. One possible implementation is by implementing the Message class like this:

public class Message
{
    // String.Empty is the null object for recipient
    private string m_recipient = String.Empty;

    // Set the "NotSet" account as the default value
    private MailAccount m_account = MailAccount.NotSet;

    public string Recipient
    {
        get { return m_recipient; }
        set { m_recipient = value; }
    }

    public MailAccount Account
    {
        get { return m_account; }
        set { m_account = value; }
    }
}

Where the MailAccount class is implemented like that:

public class MailAccount
{
    public static readonly MailAccount NotSet =
        new MailAccount("Not set", "0.0.0.0", false);

    private string m_name;
    private string m_serverAddress;
    private bool m_isSsl;

    public MailAccount(
        string name, string serverAddress, bool isSsl)
    {
        //parameter validation...
        m_name = name;
        m_serverAddress = serverAddress;
        m_isSsl = isSsl;
    }

    public string Name
    {
        get { return m_name; }
    }

    public string ServerAddress
    {
        get { return m_serverAddress; }
    }

    public bool IsSsl
    {
        get { return m_isSsl; }
    }
}

Here you can see that there is a static property called NotSet which is the null object. The field m_account is set by default to the NotSet account. The field m_recipient is set to String.Empty which also serves as a null object.

void ShowMessage(Message m)
{
    txtRecipient = m.Recipient;
    txtAccountName = m.Account.Name;
}

Because we know that both Recipient and Account are not initialized to null, we can skip the null checking and thus we get much simpler and more readable code.

One thing that I like, is that now when the account is a null object (account not set), the default values will be displayed ("Not set" and address "0.0.0.0").

A small problem with this kind of implementation is that the properties of the NotSet instance can be changed by reflection but the next part can solve that.

Another way to implement a null object is by subclassing or implementing an base interface. Based on the previous example, lets add an interface that represents an account:

public interface IMailAccount
{
    bool IsSsl { get; }
    string Name { get; }
    string ServerAddress { get; }
}

The MailAccount class will now look like that:

public class MailAccount : IMailAccount
{
    private string m_name;
    private string m_serverAddress;
    private bool m_isSsl;

    public MailAccount
        (string name, string serverAddress, bool isSsl)
    {
        //parameter validation...
        m_name = name;
        m_serverAddress = serverAddress;
        m_isSsl = isSsl;
    }

    public string Name
    {
        get { return m_name; }
    }

    public string ServerAddress
    {
        get { return m_serverAddress; }
    }

    public bool IsSsl
    {
        get { return m_isSsl; }
    }
}

Pay attention that the class now implements the IMailAccount interface and it does not contain the null object static field. The null object is implemented like this:

public class NullMailAccount : IMailAccount
{
    public NullMailAccount() {}

    public bool IsSsl
    {
        get { return false; }
    }

    public string Name
    {
        get { return "NotSet"; }
    }

    public string ServerAddress
    {
        get { return "0.0.0.0"; }
    }
}

and then the Message class will look like like this:

public class Message
{
    private static readonly IMailAccount
        MailAccountNullObject = new NullMailAccount();

    // String.Empty is the null object for recipient
    private string m_recipient = String.Empty;

    // Set the mail account null object
    private IMailAccount m_account = MailAccountNullObject;
    ...

The usage of the Message class remains the same.

This implementation is also safe for reflection since the NullMailAccount class has no fields to change and in the class message, the field MailAccountNullObject is a readonly field which can’t be set by reflection.

So to conclude, the points that I liked the most about the null object pattern are:

1) Reduces significantly the chances of getting a null reference exception.

2) Defines a common behavior for fields that were not set yet such as the case of a common value to display.

Design by contract

December 6th, 2007

Well, just wanted to point out the existence of it but there is no need rewrite a perfectly written post so read it, NOW!

The Specification Pattern

December 5th, 2007

This post is based on this post, which is a great post in my opinion and since it already exists I didn’t see the need to rewrite the post so I suggest you go read it first.

The stuff that I am going to add are few observations I have and small implementation enhancement that I think helps the implementation to be even more intuitive.

First, a small overview.

Say you have a class User who has a name, country of residence and a birth date.

It makes sense that you have something like:

if (user.CountryOfResidence == Country.Chad ||
    user.CountryOfResidence == Country.Sudan)
{
    // Do something...
}

This code performs some special logic for a user that is coming from Africa and from a country that exists in our system. There is a good chance that code such as this condition is duplicated in a UI page and in a business logic service and maybe in some more places throughout the application. The problems with this are:

Unless the developer who wrote the code added documentation that states it checks that a user came from Africa, we can only guess what it means. It might just be a list of countries for all we know… You might say that it can be placed in a local private method like

if (IsUserFromAfrica(user))
{
    // Do something
}

so now it describes what it means but this still doesn’t solve the code duplication problem. What if now Angola is supported as an African country as well? You will still have to go and change all the occurrences of the condition whether it is inline or wrapped in a method.

By using the Specification Pattern the code will be transformed to this:

if (new UserFromAfricaSpecification().IsSatisfiedBy(user))
{
    // Do something...
}

Where UserFromAfricaSpecification is implemented like this:

public class UserFromAfricaSpecification :
    Specification<User>
{
    public override bool IsSatisfiedBy(User obj)
    {
        return obj.CountryOfResidence == Country.Chad ||
            obj.CountryOfResidence == Country.Sudan;
    }
}

The base class Specification can be found in the attached code.

By working with specifications like that, we get documented, reusable  and independently testable "libraries" of specifications.

Since conditions usually are business rules, which are always difficult to maintain and manage, the specification pattern comes very handy and this is the one thing I like the most about it.

As I wrote before, this post shows how the code is built. The code sample attached to my post is almost identical to the code there. The difference is mostly in one detail - specification composition can be performed using the & and | operators, and the ! operator is also available. This means that you can write a specification like this:

if ((new UserOlderThanSpecification(18) &
    (!new UserFromAfricaSpecification())).IsSatisfiedBy(user))
{
    // Do something...
}

Another use of the specification pattern is to define what we are looking for. The signature of the IsSatisfiedBy method matches the Predicate delegate signature and therefore can be used by the ForEach method of Array or List<> when looking for, say, a user who satisfies a certain condition:

List<User> africanUsers = allUsers.FindAll(
    new UserFromAfricaSpecification().IsSatisfiedBy);

where allUsers is of type List.

What I still don’t like about the current implementation is the fact the the new keyword is used to instantiate a specification instance. I have few ideas about that so expect a follow-up.

The example code for this post is here.

Creative operator overloading

December 3rd, 2007

This post is based on two facts about C#:

1) An operator is a method. It is a static method that receives 1 or 2 parameters, depends on the operator and returns a value.

2) The return value can be anything you want it to be. Usually the operator == returns a boolean, but it can return any other data type.

The example I will show is about searching for a value in a generic list.

The .net generic list has a method called FindIndex with the following signature:

public int FindIndex(Predicate match);

Predicate is a delegate that receives a parameter of type T for evaluation and returns a boolean in case the that there is a match according to the logic defined by the predicate. This works like This:

int indexOfUserToLookFor = usersList.FindIndex(delegate(User u)
{
    return u.FirstName == userToLookFor.FirstName &&
        u.LastName == userToLookFor.LastName;
});

where usersList is defined as List and User is a class. The code above is not so elegant or readable. Having something like:

int indexOfUserToLookFor =
    usersList.FindIndex(Where.User == userToLookFor);

would be much nicer and certainly more readable.

In order to enable such syntax, the two fact about operator overloading mentioned above come to play. The code:

public class UserQuery
{
    public static Predicate<User> operator ==
        (UserQuery ignored, User other)
    {
        return new Predicate<User>(delegate(User u)
        {
            return u.FirstName == other.FirstName &&
                u.LastName == other.LastName;
        });
    }
    ...
}

does the trick. What this code means, is that when the operator == is used for object of type UserQuery (left hand side) and User (right hand side), return a Predicate that contains the logic to match a user. Pay attention that the UserQuery parameter is named ignored since it is indeed, ignored. The predicate that is returned is the same as the predicate in the first FindIndex snippet therefore the functionality is the same.

The Where in the phrase ‘Where.User == userToLookFor’ is just for nicer syntax. It is implemented simply as:

public static class Where
{
    public static UserQuery User
    {
        get
        {
            return new User.UserQuery();
        }
    }
}

This post was inspired by the code generated using the NHibernate Query Generator which uses this technic extensively. For an example of code by the NQG look here.

The complete code example for this post can be downloaded here

Tip of the day: DictionaryAdapter

November 25th, 2007

The is a part of the Castle project but can be used as a standalone assembly.

The dictionary adapter lets you wrap a dictionary with an interface definition and access that dictionary through the interface. This gives the advantage of typed data access on top of a dictionary and don’t forget the intellisense in the IDE.

The example I will use shows the use of a dictionary adapter in order to enable access to configuration data.  It contains a class:

/// 
/// This class uses configuration.
/// Instead of accessing the configuration directly,
/// it receives it in the constructor.
/// 
public class DataBaseAccess
{
    private IDataBaseAccessConfig m_config;

    /// The configuration that
    /// this class uses to access the database.
    /// 
    public DataBaseAccess(IDataBaseAccessConfig config)
    {
        m_config = config;
    }

    public void ConnectToDataBase()
    {
        Console.WriteLine("Server Ip: {0}", m_config.ServerIp);
        Console.WriteLine("DataBase: {0}", m_config.DataBaseName);
        Console.WriteLine("User: {0}", m_config.UserName);
        Console.WriteLine("Password: {0}", m_config.Password);
        Console.ReadLine();
    }
}

As you can see, this class expects a config object that implements the the IDataBaseAccessConfig interface. This interface is defined as:

/// 
/// Defines the data for data base access.
/// 
public interface IDataBaseAccessConfig
{
    string ServerIp { get;}
    string DataBaseName { get;}
    string UserName { get;}
    string Password { get;}
}

In the example, the database access data is defined in the appSettings section of the application configuration file. In order to pass it to the DataBaseAccess class, it is being wrapped like this:

// In real world example the factory should be cached.
// Create the adapter on top of the configuration dictionary.
IDataBaseAccessConfig configAdapter =
    new DictionaryAdapterFactory().
        GetAdapter(configData);

where the configAdapter is passed.

Now what happened here? The DictionaryAdapterFactory emit code in runtime that implements a wrapper class that implemets the IDataBaseAccessConfig interface and this class, when a property is being read, gets the value for the dictionary that is wrapped, in this case, the configData dictionary.

What is it good for?

1) In my opinion, it is nicer to access an interface rather than passing a configuration dictionary to the class which involves querying the data by using string literals.

2) When passing the data through the constructor instead of accessing the ConfigurationManager directly in the code we make our code better by preventing access to singletons, therefore making the code testable and agnostic to the real implementation, may it be the application configuration file, configuration defined in the database or any other implementation.

3) Intellisense…

The example solution is here

Tip of the day #2: Dynamic proxies

November 25th, 2007

A dynamic proxy is an approach that is not fully natively supported in .net but natively exists in java.

What a proxy means, is to wrap an object with with wrapper that intercepts call to that object and does something in addition.

What is it good for? A naive example is to add a proxy that log calls to methods of an object.

A more real world example is to use proxy in an O/R mapper. The mapper can create proxies on top of the domain object and intercept calls to properties in order to fetch data from the db and track changes to the data that will later be persisted (NHibernate works this way).

The idea of dynamic proxy is to provide an implementation of an interceptor and attach it to the proxy. From now on, all calls to methods will pay through the interceptor which, for the logging example, logs every call to the method. Concrete examples can be found in the link at the bottom of this post.

The .net native implementation for dynamic proxies is by using ContextBoundObject or MarsalByRefObject. This approach is limited since you have to inherit from one of these classes which is not clean.

There are several implementations of dynamic proxies that do not interfere with inheritance hierarchy of your code.
Here are some examples:

1) Castle DynamicProxy

2) DynamicProxy.NET

3) LinFu

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