Reshef’s tip of the day

.net development tips

Archive for the ‘c#’ Category

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.

Design by contract

Thursday, 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

Wednesday, 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

Monday, 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: Friend assemblies

Sunday, November 25th, 2007

The internal keyword (C#) is defined as the way to restrict access to members only to types in same assembly.

But, since the .net framework 2.0, there is a way to to define an assembly as a friend assembly. This can be done by specifying

[assembly:InternalsVisibleTo("friend assembly")]

in the AssemblyInfo.cs file (or in any other file).

After specifying this, the friend assembly can access the internals of the assembly marked with this attribute.

I can see two useful thing that can be achieved:

1) Better encapsulation of course.

2) Enable access for unit testing by using this strategy.

The msdn documentation is here.

Tip of the day #2: ref/out key words for reference types

Sunday, November 25th, 2007

This tip is the courtesy of Gal.

It surprised and embarrassed me to realize that I didn’t know it.

When a reference type is passed to a method without using the ref or out keywords, a new reference is created inside the method and it points to the same location in the memory as the reference that was passed so we have two "pointers" to the same location in memory.

In case the the reference inside the method is set to a different location, the reference that was passed does not change.

When the ref/out keywords are used, we have only one reference inside and outside the method so if the reference is changed to point to another location and it happens inside the method, the outer reference is changed too.

Basic stuff…

Tip of the day: Data Type aliasing

Sunday, November 25th, 2007

There is a feature in .net that is not commonly remembered and it is Data Type aliasing.

What it means is that u give a data type a different name.

I can see two uses for it:
1) Enhance code readability:

Instead of having very long type declarations such as when using generic types inside generic types, u can assign an alias to that declaration. Here is an example:

    // Aliasing
    using HashOfHashes =
        Dictionary>>;

    public class AliasExample
    {
        HashOfHashes m_hash;

        public AliasExample()
        {
            m_hash = new HashOfHashes();
        }

        public HashOfHashes MyHash
        {
            get
            {
                return m_hash;
            }
        }
    }

2) Alias data types that are prone to change:


An example is an identifier property of class. It can save a lot find&replace when changing code like changing the identifier of a member from int to Guid and it better shows intent. For example:

    // Aliasing
    using MemberIdentidfier = Guid;

    public class MemberWithAlias
    {
        private MemberIdentidfier m_id;
        private string m_name;

        public MemberWithAlias
                (MemberIdentidfier id)
        {
            m_id = id;
        }

        public MemberIdentidfier Id
        {
            get { return m_id; }
        }

        public string Name
        {
            get { return m_name; }
            set { m_name = value; }
        }
    }
Jajah is the VoIP player that brought you web-activated telephony.