Monthly Archives: October 2011

Delegates Explained – Part 4

The Delegates Series:

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

In this last post in this series, I want to examine what the event keyword buys us in the subscriber model for handling events.

Consider our previous example. Recall that the notification delegate of the DvdStore class is public. Now, what would happen if we set the Notification delegate to a totally new delegate object? It would blow away the list of delegates which had previously been subscribed, is the short answer. Try it yourself and see.

        static void Main(string[] args)
        {
            DvdStore theStore = new DvdStore();

            theStore.notification += new NotifyDvdArrived(BroadcastArrivalOfDvdByBatSignal);
            theStore.notification += new NotifyDvdArrived(BroadcastArrivalOfDvdByLoudSpeaker);
            theStore.notification += new NotifyDvdArrived(BroadcastArrivalOfDvdBySnailMail);

            theStore.notification = delegate
                                        {
                                            Console.WriteLine("The Thing is not a good movie. " +
                                                              "Go home and take a good hard look at your life.");
                                        };

            theStore.SendOutNotification("The Thing");

            // end of app
            Footer();
        }

Line 9 is where the damage is done, publishing a sacriligious message which should be disregarded at all costs.
Now, add the event keyword on the custom delegate, keep that member public and try and set it to a new delegate object as we just did above:

            public event NotifyDvdArrived notification;

Notice how … we can’t. You will get a compile error with a message along the lines of The event ‘DelegatesExplained.Program.DvdStore.notification’ can only appear on the left hand side of += or -= (except when used from within the type ‘DelegatesExplained.Program.DvdStore’

So, with encapsulation back in tact, we now have a safe way to subscribe handlers to, and removing them from, “event” delegates. This enables the delegate to be public (which it needs to be for subscribers), but protects it from being changed/written over.

Not bad, for one little word.
Get the code:

Object Inheritance – Done the Right Way

In my last javascript post, I said that I would look at the Object.create method, which is part of the new Javascript 5.

In my opinion, this new way of creating objects is how inheritance is most natural in Javascript. Before I go into an example, I want to explain my thoughts on it.

Javascript is an object-based language. It has no classes (despite what the Microsoft AJAX library would have us believe). There is no natural construct of a class in Javascript. Only objects and prototypes. Just the word prototype itself explains it all. Object A can be a prototype for Object B. That’s how easy inheritance is with this language. Instead of class-based inheritance, it is more like, “Hey, I like that object over there. I might just make a copy of it and add some more members to it. Members that are important for the problem at hand.”

The usage of Object.create is very simple. First, lets create a person object using the literal notation.

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

Now, lets create an object dave which is created based upon the person object. We have more created an object from the person object than inherited from it. Then we added some new properties, augmenting the cloned object which we started with:

        var dave = Object.create(person);
        dave.name = 'Dave';
        dave.age = 37;
        dave.showAge = function() {
            return this.age;
        }

We can demonstrate the inheritance by displaying the number of legs of the new dave object (this property is inherited from the person object):

<input id="Button8" onclick="alert(dave.legs);" type="button" value="Show Dave's Leg Number (inherited from person)" />

You can download the example code for this post here. It contains a few more objects and demonstrates it working accordingly. Note that the Object.create method does not work in any version of IE before IE9. It is supported in the more recent versions of Firefox and Chrome. Not sure about any of the other browsers.