Archive | February, 2009

Updating an item in a list without a reference with lambdas

15 Feb

I have to confess I am enjoying lambdas a bit much. I am making this post to show a cool way of avoiding code loops (there are still loops in CLR of course).

private void UpdatePerson(Person updatedPersonObject)
{
    var outOfDatePerson = _people
            .First(person => person.Id == updatedPersonObject.Id);
    int index = _people.IndexOf(outOfDatePersonObject);
    _people[index] = updatedPersonObject;
}

private void UpdatePerson_OldCSharp(Person updatedPersonObject)
{
    int outOfDatePersonIndex = 0;
    for (int i = 0; i < _people.Count ; i++ )
    {
        if (_people[i].Id == updatedPersonObject.Id)
        {
            outOfDatePersonIndex = i;
            break;
        }
    }
    _people[outOfDatePersonIndex] = updatedPersonObject;
}

From the two code samples it is worth noticing the difference in the number of lines and in the hierarchical nature of the code. The traditional C# for loop approach (the second method) leads me to cringe from a maintenance point of view. Each line of code is highly contextual and relies heavily on multiple levels of language constructs.

The first method (the lambda way) to me is much more readable and also maintainable. There is a flat hierarchy which is much easier to read as it doesn’t involve following the loop through code. I argue it is easier to maintain as the lines can change order more and will still be doing the same thing. It is also easier to update as there is less code.

Databinding to Collections

15 Feb

If you use WPF then you will be using databinding extensively. This post looks at databinding with respect to collections.

Databinding basics (Background Info):

To databind in .NET currently you are required to provide notification of when the variables you databind to change. This can be done by implementing the INotifyPropertyChanged interface or by implementing the property as a dependency property. For more information on databinding basics, see here.

Collections are slightly different

In the case of collections it is often not important when a collection object changes but rather when the items within that collection change. With that said you will likely need both approaches implemented because if an entire collection is reassigned the binding to the observable collection will be lost as it has been replaced with a new observable collection. It is also possible that others in your team will re-assign the list at some point, so that is why I like to plan for that situation.

private ObservableCollection<String> _names;
internal ObservableCollection<String> Names
{
    get { return _names; }
    set
    {
        _names = value;
        PropertyChanged(this, new PropertyChangedEventArgs("Names"));
    }
}

 

ObservableCollection<T> notifies bindings an item has changed from its CollectionChanged event. The previous code sample shows the INotifyPropertyChanged interface implementation which is required to see if the ObservableCollection assigned to “Names” has been changed. 

In conclusion all Lists that are going to be used for databinding should be ObservableCollections. All properties that are databinded to should implement the INotifyPropertyChanged interface or be dependency properties.

Beyond Relational Databases

14 Feb

I am no expert with databases, however I can definitely see scalability issues that relational databases provide when needed to grow beyond one database. Relational databases also are strongly typed and explicit relationships exist between entities. This explicit relationship specification and strong typing often requires developers to write migration scripts which can be a pain and could potentially be avoided or minimized.

There is an interesting article: http://www.readwriteweb.com/archives/is_the_relational_database_doomed.php which discusses the benefits of key-value databases or cloud oriented databases.

Unfortunately most of these databases are in beta and the standards between them are lacking, but I can definitely see from my experience developing payroll software that a key-value database would help us in many areas.

The down sides to key-value databases are that they are weakly typed and hence there is no schema which means you can get bad data in the database, meaning that code has to deal with that possibility, which could lead to more mistakes. I do feel however that weaker typing and not specifying relationships between entities is the way of the future because if we look at C# and other modern languages we can notice a trend of moving towards more weakly typed languages.

I do prefer a strongly typed language currently however as technology progresses I can see that dynamic typing will lead to more general code that will be more flexible to change. Currently my biggest concern is that dynamically typed languages are prone to catching errors at runtime rather than compile time which is a blow for software reliability. I am confident that this can be overcome.

It is important to state that there is an overhead in specifying types/schemas and converting between types. I also think that currently developers can make assumptions in strongly typed languages that objects will be populated in a way that they expect which sometimes is not the case. With dynamically typed objects this assumption would not be exercised as it would soon become clear that less can be assumed. The immediate development areas of .NET CLR 3.5 and 4.0 show that functional programming and dynamic objects are the current direction. I also like the hybrid approach that .NET is creating by using the power of strong typing and providing facilities towards gradual introduction of dynamic typing. This will hopefully allow for existing functionality that applies to strongly typed objects to be used against dynamically typed objects.

Event Handling Techniques

13 Feb

As .NET grows so do the number of ways of tackling the same or similar problems. Event Handling is no exception.

//1
button1.Click += new RoutedEventHandler(button1_Click);
 
//2
button1.Click += button1_Click;
 
//3
button1.Click += delegate(System.Object o, RoutedEventArgs e)
                     {
                         System.Windows.MessageBox.Show("Click!");
                     };
 
//4
button1.Click += delegate
{
    MessageBox.Show("Click!");
};
 
//5
button1.Click += (o, e) => MessageBox.Show("Click!");

 

Personally I use approach 2 and 5 depending on the situation. Approaches 3, 4 & 5 are anonymous handlers which means that their name is determined at creation (so we don’t know what it is). This can sometimes be an issue if you want to unsubscribe from an event, see here. Again with this post Resharper will make suggestions to use approach 2 and 5.

I feel there is an important difference between approach 1 and 2 that should be elaborated on. Approach 1 delcares the delegate of RoutedEventHandler twice because the delegate is already specified in, and hence inferred from, the event declaration. This is shown below:

internal event RoutedEventHandler Click;

 

Inferring types rather than having duplicate definitions is important as it means that you don’t have to repeat yourself and when you refactor your code you will have an easier job updating it when it is specified once.

For those unfamiliar with delegates, delegates are method parameter contracts which in the case of RoutedEventHandler specifies that an implementer of its contract will have the parameters of (Object, RoutedEventArgs).

Implicit parameter specification with Lambdas

13 Feb

On the last line of code in the following code listing you will notice that the method of IList<T>.Add(T item) is called but with no parameter.

//our resulting output
IList<Person> lecturersEnrolledForStudy = new List<Person>();

//students and lecturers can enrol for study.
var newStudentEnrolementList = new List<Person>();

//filter the students out
var lecturersEnrollingInAClass = newStudentEnrolementList
                                    .Where(person => person.isLecturer)
                                    .ToList();

//add lecturers that are enrolling to the enrolled list.
lecturersEnrollingInAClass.ForEach(lecturersEnrolledForStudy.Add);

The parameter is still being populated like as if the following code was written:

lecturersEnrollingInAClass
            .ForEach(item => lecturersEnrolledForStudy.Add(item));

The parameter is inferred by the compiler just as the type of the “item” variable is by the lambda expression/list type. For those of us who are being weaned off traditional loops for these sorts of list interactions might find that it is more natural to think of the list that we are adding too first, and the list that the information is coming from second. This has reversed with lambdas.

A point worth making is that while this example I have provided is simple and could be done using an AddRange method, it is not as extensible and hence I suggest not using it. An example of the .ForEach extention methods extensibility would be that it can ‘addrange’s across different types and at different depths of objects. An example of this could be:

lecturersEnrollingInAClass
            .ForEach(item => lecturesNamesList.Add(item.Name));

In conclusion this is a handy shorthand to use with lambdas. If you already use the Resharper plug-in, this shorthand will have been suggested to you.

LINQ for show, Lambda for pro

13 Feb

When first utilizing the new query techniques of .NET 3.5 such as LINQ and Lambda expressions I would always choose LINQ over lambda expressions. This was for two reasons:

1. LINQ looked more natural

2. Lambda expressions or the LINQ extension methods to be more accurate are often hidden away because either you are not using the correct type to access them, or don’t have the System.LINQ library in the using section.

As time has progressed I have realised that I now use lambda expressions almost exclusively. I feel that looking deeper into LINQ has facilitated this, specifically understanding the typing behind LINQ. Ultimately it comes down to preference as the compiler changes LINQ to use extension methods, see: here

An example of the difference in sytnax is:

var d = (from mp in MyProducts

where mp.Price < 50d

select mp);

var f = MyProducts.Where(mp => mp.Price < 50d)

I think that when your queries are smaller, that lambda expressions are quicker to write and more natural to the rest of C#. When a query becomes very large LINQ could be more concise but I haven’t yet come across such a situation. Also I am not a fan of single huge queries as it is an inconvenience for other developers if they need to modify a query. Its bigger, so takes longer to read, and multiple smaller queries means that code be executed in between queries. With PLINQ however there could be an advantage in have a single larger query, however I am not taking PLINQ into consideration today.

Why we Blend & Custom combo boxes

5 Feb

I have been sceptical of Expression Blend for a while now. I have found that it is was a marginally better designer than Visual Studio and I didn’t see what the fuss was about. Yesterday I found out a massively powerful feature that now I wouldn’t develop WPF without. The feature I am talking about is the ability to copy existing styles from framework controls such as  a combo-box and change them. This is best demonstrated at the following blog: http://www.designerwpf.com/2008/10/01/how-to-use-a-listview-or-datagrid-in-a-combobox-drop-down-without-a-line-of-code/. For that blog tutorial you don’t need to add a reference like the tutorial asks if you aren’t going to use a datagrid control.

One thing to be careful of is that there will be two item presenters in the template. If you are like me and wanted to make a customizable combo-box drop down but also have the selected item area update then you will need to make your control isEditable=true and isReadOnly=false. This will use the opposite ItemPresenter once isEditable is changed to true. This initially gave me a fright thinking that I would not be able to use isEditable.

If multiple selection is wanted in your custom combo box you can try: http://jobijoy.blogspot.com/2009/02/simple-multiselect-combobox-using.html