Dean's Coding Ladder

Yet another .NET Blog

.NET delegates and the Observer pattern

leave a comment »

Usually, the first thing you learn about the .NET delegates is that they are “type safe function pointers”… As you continue reading your .NET book of choice covering your .NET language of choice, you learn that delegates are used to hold reference(s) to one or more functions that  are to be invoked when needed. You learn how to create delegates, register and un-register functions and so on…

In short, you learn the mechanics of how the delegates are created and used but if you are a beginner trying to learn all this on your own with limited or no OOP background or expert guidance you are most likely confused and wondering why do you even need the delegates when you can just call all these methods directly…

I’ve been in that boat not so long ago so this is my humble attempt to give back a little and hopefully help out anyone out there who is learning .NET programming on their own and might be wondering what exactly is the purpose of these delegates and why use them at all.

Anyway, if you are indeed confused with the whole concept of delegates and all these articles you keep googling out are not helping you understand the concept any better, the chances are you are at that stage where your programming mindset is still procedural which is a quite common initial mindset for self-thought developers. In other words, when you think about inner workings of your programs you are thinking in terms of distinct steps your programs must perform in order to achieve something, perform some function, generate some output… There is nothing wrong with that approach and there are lots of great pieces of software that are written in that fashion and lots of developers who still make a living programming like that. However, in that procedural world delegates are of limited value.

Delegates become immensely valuable though, once you start switching to OOP mindset (which is something I highly recommend after doing the same myself) and start resolving problems posed by objects and their interactions and internal state(s) that are of such importance to some other objects that they must be notified when these state(s) change.

Once you are presented with this new set of unique OOP challenges one of the most important core programming principles, the one urging you to avoid reinventing the wheel all the time, should kick in and lead you towards design patterns and once you learn about the Observer pattern the alarm should go off and arguably the most important purpose of delegates should become crystal clear.

A few words about the design patterns first…

Let’s say you are tasked to build a simple internal combustion engine. You’ve never done anything like that in your life and have no clue what it takes to design and build one but you know very well that internal combustion engines have been around for over a hundred years and your best bet is to tap into that existing knowledge instead of trying to design everything on your own from scratch. You purchase a couple of books about internal combustion engine design and pretty soon you realize that all these engines are essentially the same and that you need the engine block with several holes for pistons, a cam or two, some pistons and bunch of other parts. All these parts interact and are connected to each other in order to allow this engine to do its job.

The sum of these parts and their interactions and the best way to put the whole thing together in order to get the desired result is a design pattern that you can observe in any internal combustion engine with some modifications and they all inherit most important components and design patterns from the first modern design internal combustion engine that was ever built…

Just like there are design patterns for pretty much any machine that was ever engineered there are many different design patterns that can be applied to your OO software to solve common OO design challenges and prevent you from inventing the wheel over and over again. The time spent learning these design patterns helps you immensely down the line when you are faced with these design challenges in your object oriented world.

One of very important design patterns is the aforementioned Observer pattern and .NET delegates are perfectly suited to help with observer patterns you will need to implement in your .NET OO projects. The essence of Observer pattern is very simple and it is all about objects being notified when some aspect of the internal state of other object(s) that are important to them is changed and if it wasn’t for delegates in .NET you would have to implement the Observer pattern the old fashioned way producing more code that is less readable and compact.

A little bit about events now…

One of the challenges that all self-thought .NET developers are facing stems from often excessive user-friendliness of our beloved Visual Studio which tends to promote some bad habits and tunnel vision.

When you first start working with VS it is so easy to get sucked into just dragging those buttons, checkboxes, treeviews and other controls over to the design surface and than double-clicking on them to let the VS IDE create events, properties and methods for you. Pretty soon you’re under the impression that is all there is to events… users clicking on these controls of yours and firing events. There is so much more to events than that however and it is important to keep in mind that events are not just something that happens in response to user actions in your UI…

For example, if you were building an application to be used by sales reps of some very dynamic on-line retailer, it is quite easy to imagine a situation where several reps would be trying to sell the same bestselling item that just happens to be currently low on quantities to different customers at the very same time. In such a scenario it would be very important that your UI would promptly update the quantities as soon as one of the reps finalizes a sale so that other sales reps would immediately know if it is okay to proceed with their sale or not. Such a system would probably have an object in the data access layer that would query the database at the frequency established by your algorithm that takes into account how many sales reps have the same item open at the same time, how many items remain in storage and how ‘hot’ the item is. Another object in your business logic layer would communicate with this data access layer object and store these available quantities in some variable or a container that is a part of its internal state. On top of that, one or more objects in your UI would need to be updated as soon as the quantities in that business logic layer object are modified. All these objects would therefore need to communicate by implementing the Observer pattern and in the .NET world the best way to do this is via delegates and events.

The UI objects that display the quantities to the rep would in this context become observers and would have to register with the business logic layer object to be notified when its state related to available product quantities is changed. The data access layer object that queries the database would need to ‘observe’ some other business logic layer object that keeps track of how many reps have the item open in order to establish how often it should query the database and so on and so fort…

Obviously the exact implementation details could be completely different from what I described here as there is always many different ways to do the same thing but the bottom line remains the same and that bottom line is that in the world of Object Oriented Programming objects often need to be notified when internal state of some other object is modified and that is where the delegates and events become very important since the best way to implement the Observer pattern in the .NET world is precisely by using the delegates and events.

Hope this helps clear up your delegate haze… happy engineering…

Written by Dean K.

2009/07/10 at 22:22

Multiple DBML Files sharing tables

leave a comment »

Creating LINQ to SQL DataContexts in Visual Studio is as easy as dragging and dropping tables into a LINQ to SQL DBML file.

However, one of many possible causes of confusion for all of us who like to learn by trial and error might be trying to add one table to multiple DataContexts… If you try that you’ll get a nice compiler error when you build your solution…

At first I thought this was a limitation of LINQ but then I stumbled upon this LINQ to SQL FAQ and learned that there is no such a limitation in LINQ and all you need to do is make sure that your Context and Entity namespaces are distinct values for each DBML file.

This is IMO a very important piece of information as it allows you to have multiple logical DataContexts with smaller sets of tables which sometimes overlap instead of one really big DataContext that you have to instantiate every time you need to use LINQ to query your SQL database…

Written by Dean K.

2009/05/06 at 04:39

Follow

Get every new post delivered to your Inbox.