Monthly Archives: June 2011

Delegates Explained – Part 1

I thought I would write a small series of articles on delegates for students. I can recall as a student, how I learnt many things from blog posts of enthusiastic developers.

The Delegates Series:

  1. Delegates Explained – Part 1 <<
  2. Delegates Explained – Part 2
  3. Delegates Explained – Part 3
  4. Delegates Explained – Part 4

I will firstly explain what delegates are. Then I shall go through various code examples to show the syntax for their use. The series will start off with the basics and evolve the concept of delegates in bite-size chucks.

What is a Delegate?

From a (very good) textbook*:

a delegate is a type-safe object that points to another method (or possibly a list of methods) in the application, which can be invoked at a later time. Specifically speaking, a delegate object maintains three important pieces of information:

  • The address of the method on which it makes calls
  • The arguments (if any) of this method
  • The return value (if any) of this method

What this gives us is a type-safe way to implement callbacks.

Tangent! What is a Callback?
I think of callbacks like this (using humans as an analogy): I say to you, “Here, take this phone number. Now go off and do a task and when you are done, ring this number.” Or if we are talking asynchronous, “Here, take this email address. Now go off and do a task and when you are done, send an email to that address.” The act of ringing that number, or sendng that email, is the callback.

Ok. We’re back.

An Example – The DVD Store Notification Subscription

I’ll go through a simple example in this post. There is a DVD store which we want to tell us when a new DVD arrives. So, we are going to subscribe for that. The DVD store says to the world at large, “If you provide us with a notification method that adheres to a certain specification, then we will notify you of new releases using that method.” In this case, the specification for that method is the delegate called NotifyDvdArrived.

        public delegate void NotifyDvdArrived(string title);

This requires the method to have a void return type and take a single string parameter. Lets take a look at the DVDStore class:

        public class DvdStore
        {
            private NotifyDvdArrived notification;

            public DvdStore()
            {
                // default constructor
            }

            public void SubscribeMeForNotifications(NotifyDvdArrived notificationMethod)
            {
                notification = new NotifyDvdArrived(notificationMethod);
            }

            public void SendOutNotification(string titleOfDvd)
            {
                notification.Invoke(titleOfDvd);
            }
        }

The SubscribeMeForNotifications method is the one by which we can tell the DVD Store that we want to receive notifications. It takes a NotifyDvdArrived delegate as a parameter which enables us to tell them how we want to receive that notification. As the name suggests, the SendOutNotification method is what the DVD store uses to broadcast its notifications. Any object that has subscribed to receive notifications will do so in the way in which it has specified to do so, when it subscribed for the notification (I will show how more than 1 object can subscribe in a future post).

The contents of the Main method are quite simple:

        static void Main(string[] args)
        {
            DvdStore theStore = new DvdStore();
            theStore.SubscribeMeForNotifications(new NotifyDvdArrived(BroadcastArrivalOfDvd));

            theStore.SendOutNotification("The Thing");             
            
            Footer();
        }

We (the Main method) go to a DVD Store, subscribe for notifications, and we do so supplying the BroadcastArrivalOfDvd method, which is:

        private static void BroadcastArrivalOfDvd(string titleOfDvd)
        {
            Console.WriteLine("The Dvd called {0} has arrived.", titleOfDvd);
        }

Looking back at the SendOutNotification method, it calls the Invoke method of the delegate object which calls (calls back) the BroadcastArrivalOfDvd method which we subscribed with, passing it the string parameter which is passed to SendOutNotification.

What’s the Benefit?

Delegates allow us to decouple, which is the first step to a scalable, maintainable architecture. This benefit will probably be lost on you students, until you enter the world of enterprise development. Translation – just trust me, it’s a good thing.

In my next Delegates post, I will take the example a little further to unlock a few more features that you need to know about delegates. The source code for this article can be
downloaded here:

*Andrew Troelsen’s Pro C# 2008 and the .NET 3.5 Platform at p.341

Object Inheritance – An Interesting Pitfall

There are a few more points which I want to make as an addendum to my last post on inheritance in Javascript.
Starting again with our person object, we will make a couple of constructor functions Man and Woman:

        // using the object literal notation, create a person object
        var person = {
	        legs: 2,
	        arms: 2,
	        getName: function(){
		        return this.name;
	        }
        }    
        
        function Man (){}
        function Woman (){}

Now lets add the code to set up the inheritance i.e. set the prototype property of the two new constructor functions to the person object:

        Man.prototype = person;
        Man.prototype.constructor = Man;
        Woman.prototype = person;
        Woman.prototype.constructor = Woman;

The other thing which we have done there is to set the constructor of the prototype of those constructor functions back to the relevant constructor function itself. The reason for that is because their constructor function would otherwise become the Object constructor function i.e. the constructor function of the person object (which was set as the prototype of the constructor functions). The relationship is circular in nature by design – remember, this is a functional language.
The problem we run into is – what happens when we ask an object created using one of these functions, “What type of object are you?”

        var dave = new Man();
        dave.favouriteBand = 'the black crowes';
        dave.job = 'code monkey';
        dave.name = 'dave';

        // hey dave object, what are you?
        document.writeln(dave.constructor);

And the answer is function Woman() { }. What?!
OK. Here is what happened.

  • we set the prototype of the Woman constructor to person
  • we set the Constructor of the prototype of the Woman function to Woman

As you will recall, the prototype of the Man constructor was the exact same object (the person object) as the prototype of the Woman constructor. I’ll repeat that a different way for clarity – the person object is the prototype of both constructor functions (Man and Woman). As a result, if you change something on that object, the change will cascade to the Woman and Man constructor functions. To rectify this, you can replace the person object literal with a Person constructor function.

        // using a Constructor function
        function Person() {
	        this.legs = 2;
	        this.arms = 2;
	        this.getName = function() {
	            return this.name;
	        };
        }  

Then, we can use that function in setting up the inheritance. Remember to use the new keyword. Also remember, the prototype is an object, not a function. So we create an “instance” object using the constructor function Person. This will ensure that each of the Man and Woman constructor functions will get their own unique object as a prototype.

        function Man (){}
        function Woman (){}

        Man.prototype = new Person();
        Man.prototype.constructor = Man;
        Woman.prototype = new Person();
        Woman.prototype.constructor = Woman;

Now, if we add that remaining code again, we find that dave is a man:

        var dave = new Man();
        dave.favouriteBand = 'the black crowes';
        dave.job = 'code monkey';
        dave.name = 'dave';

        // hey dave object, what are you?
        document.writeln(dave.getName() + '
'); document.writeln(dave.constructor + '
');

But even this does not feel right. We are creating separate prototype objects for the two child constructor functions. And the whole idea of using a prototype-based inheritance v.s a class-based inheritance is to use the one object, and share various properties and methods amongst many child objects. The approach above looks and feels very much like a class-based inheritance paradigm; even though there are no classes in Javascript.

In a future post, I will speak about the new Object.create method in ECMAScript 5.

Edit 20 July 2011: Note that the Person function constructor still has the constructor function Function. In the example above, because we used the new keyword, the constructors of objects created by the Person constructor were changed to Man and Woman. Not the constructor of the Person function itself!

Inheritance and Secret Links – the Javascript Way

Inheritance in Javascript is a bit of a mess. This stems from the fact that a functional, prototypal language has been shoe-horned in to a c-like syntax. Lets take a look at the default inheritance pattern which is set out in the offical ECMA standard.

We will create a person object and use it as a prototype for creating men and women objects.

		// using the object literal notation, create a person
		var person = {
			legs: 2,
			arms: 2,
			getName: function{
				return this.name;
			}
		};

        function Man {};
        function Woman {};

        Man.prototype = person;
        Woman.prototype = person;

Next, we will create a Man and a Woman object and view their various properties:

        var dave = new Man();
        dave.favouriteBand = 'the black crowes';
        dave.job = 'code monkey';
        dave.name = 'dave';

        var beth = new Woman();
        beth.hobby = 'yoga';
        beth.pet = 'dragon';
        beth.name = 'beth';

        document.write(dave.favouriteBand + '<br />');
        document.write(dave.job + '<br />');
        document.write(dave.getName() + '<br />');
        document.write(beth.hobby + '<br />');
        document.write(beth.pet + '<br />');
        document.write(beth.getName() + '<br />');
        document.write('<br />'); document.writeln('<br />');

Note that we called the getName() method of the parent person object, which was accessible to the children objects. We can also check the other parent properties:

		//  access the parent properties
        document.writeln(dave.arms + '<br />');
        document.writeln(beth.legs + '<br />');

This all looks great. So what’s the problem?
Lets trash the dave object’s constructor.

        dave.constructor = 'dave has been trashed';
        document.writeln(typeof (dave.constructor.prototype));

It is now a string value, rather than a constructor function. Just as we would expect.
So, now that the constructor function is gone, does dave still have a name?

            document.writeln(dave.getName() + '<br />');

getName() returns Dave’s name! What? How? If we trash the constructor, and thereby break the chain of inheritance, how come we can still call the getName() method?

Well, whilst we use the prototype property to implement inheritance in the ECMA way, something is going on under the covers which maintains the chain of inheritance. There is a “secret” link which the dave and beth objects get upon their creation, which point to the person object. This link is maintained, even if the constructor property of those objects is written over.

How can I see this? Prove it! OK. Well, first, you need Firefox. Not because it is the best browser. But because its implementation of javascript exposes this secret link as the __proto__ property. You can see it using Firebug:

The __proto__ Link

The __proto__ Link

Whilst you can access this property in Firexfox, you should never do so, as your code will not be cross-browser (and pssst – it’s meant to be secret). In any case, with proper design, you should never need to. The point of this investigative probing is to highlight the quirky nature of inheritance in the language. Now that we are aware of it, we can code around it!

In my next javascript post, I will point out another interesting thing or two to note about inheritance in javascript.