Twitter Feed: @definition6

DEFINING INSIGHTS

Architectural Diary - Refactoring Minefields

Monday, March 28, 2011 by Jonathan Taylor

Change sucks. I’ve heard the glib rhetoric and seen the shiny happy bumper stickers proclaiming the staunch opposite. They're often paired with an equally shiny sticker of a cat skeleton with a smiley face stuck to the front of it. "Change is good," but apparently not for the cat.

Now, I’ll admit, for some things, change is a genuinely welcome event – underwear, socks, cat litter, and most immediately my empty pint glass come to mind. However, with web application development change sucks! Change means long nights rolling in new code to replace old. Change means endless cycles refactoring someone else’s code, often on shoestring documentation and littered with dependencies you don’t know about until you trip over them. How often have you fixed one bug and 3 more pop up? Poorly written code, like it or not, is a fact of life.

Blame it on too many requirements in not enough time, or whatever you want to, but the sad truth is most developers build what they have to without thought of what it takes to support it once it’s running. If it’s your task to have to go back in and add a new feature or change existing functionality, yeah, change sucks. And the number one culprit in contributing to code sucky-ness is dependency. Updating heavily dependent code is like planting corn in a minefield, you might get a few new stalks in ok, but it’s only a matter of time before something’s going to blow up.

So, how can we, as developers, do eachother right and make sure the code we write won’t blow somebody’s refactoring effort to smithereens? Especially if it might actually be us doing the refactoring? Limit dependency in our own code! Right! Ok, so how exactly do we do go about building projects that aren’t refactoring minefileds? Glad you asked.

The easiest way to reduce dependency between two pieces of code is through a façade. Let’s go with an example. Take a look at the code in Segment 1.

Code Segment 1.

    class Example

    {

        //Default constructor

        public Example()

        {

 

        }   

        //Public method

        public void DoSomething(String thing)

        {

            //process thing

        }

    }

    public class Caller

    {

        String stuff = "stuff that needs to be done";

        Example xmpl = new Example();

        xmpl.DoSomething(stuff);

    }

 

Pretty standard stuff, right? A simple Caller class that instantiates a version of our Example class, then calls the Example class’ DoSomething() method. Pretty standard, you’ve probably written hundreds of similar code sets. But what if we had to update DoSomething()’s code to include some new functionality once it had been pushed into production? We’d have to change both our Example class, our Caller class, and anybody else that was dependent on Example to do something. Total pain.

Now, there are lots of ways we can reduce our caller class dependency in our example class. We could setup a factory to handle the instantiation of the example class, throw in some dependency injection, or heck, even define an interface we could program all our caller classes to [Love interfaces. Love them. Separate declaration from implementation in one easy step. But sadly, it’s another post…JT], but our intent here is relate to you just how easy it is to separate the declaration of our DoSomething() method from its processing through a simple façade, and in so doing significantly reduce the dependency any class implementing our Example class has to deal with. Let’s get to it.

What we’re going to do is use a really easy implementation of the Façade Pattern which Microsoft itself uses extensively throughout its .NET framework – a Non-Virtual Interface (NVI).

Oooo. Aaaahh.

Ok, big name for really simple solution to break dependency between entities. Basically what an NVI is a public method declaration that calls a private internal method to carry out its processing. I know, sounds too easy right? Right! It is! But what it does for us is cleanly separate declaration from implementation.

Oooo. Aaaahh.

Ok, I’ll stop, but this is wicked cool stuff. Check out Segment 2

Code Segment 2

    class Example

    {

        //Default constructor

        public Example()

        {

 

        }   

        //Public method

        public void DoSomething(String something)

        {

            DoSomethingElse(something);

        }

        //Private method to do processing

        public void DoSomethingElse(String somethingElse)

{

            //process something else

}

    }

 

    public class Caller

    {

        String stuff = "stuff that needs to be done";

        Example xmpl = new Example();

        xmpl.DoSomething(stuff);

    }

 

Again, it looks too easy, doesn’t it? In fact, if you don’t stop to think about what this code is doing for us, you’ll miss it, it’s that easy. Say we had to support some new corporate mandate in our DoSomething() method once it had already been released? [We have to log everytime someone does something! Log it! Log it I say!] Well thanks to our tidy NVI, all we have to do is go into our code, and add the new logging functionality to the private DoSomethingElse() method, and we’re done. Done! Our Caller class doesn’t have to be touched because its method call into DoSomething() hasn’t changed!

It’s starting to make sense, right?

So, exposing a public interface which calls a private implementation is the core of what a Façade Pattern is, and a Non-Virtual Interface is a neat trick you can use to keep your own code separated and dependency-Free.

Oooo. Aaaahh.

Sorry, couldn’t resist. Imagine how much easier your refactoring efforts would be if all your existing projects implemented NVIs throughout their codebase? Would certainly reduce the number of senseless refactoring minefield injuries, wouldn’t it? Oh yes it would.

Life might acutally be pretty good. Change would still definitely suck though.

Architectural Diary - The Future of Web Development

Monday, March 21, 2011 by Jonathan Taylor

Web application development is on the precipice of a revolution; through a confluence of independent practices and technologies, the way in which web applications are built and consumed is about to change radically.

What is happening is a fundamental shift away from the current state-heavy, page-based processing model to a loose collection of lightweight web-based services that an empowered client can consume to provide full functionality in a composite fashion. It started with AJAX, grew substantially with MVC, took shape with REST, and is now about to break wide open.

Web development up to this point has been tied very closely to processing HttpRequests on a page-by-page level. Remember classic ASP and ColdFusion with code intermixed with html on the page? [Honestly, was there ever a worse language to work with than VBScript? If…EndIf…Next? Please. Microsoft still owes the development community a sincere apology for making us suffer through the miserable excuse for a language that was VBScript – JT] Nightmare! ASP.NET brought the separation of code and markup, which was a huge advancement, but brought along with it a heavy page-processing model and cumbersome state management tied to the server, or worse, hashed and embedded in the page itself. [He’s using ViewState! Grab your torch and pitchforks! Raah!]

AJAX was the emancipation proclamation that freed web development from the confines of postback processing. Utilizing the substantially overlooked XMLHttpRequest object [Thank you Microsoft for developing the XmlHttpRequest in 2000 but not incorporating it into a browser until 2006], developers were suddenly free to call back into their server for processing without having to post an entire page’s content and wait for it to come back. In its entirety. Which took time. Like reading this. OK, you get the point. AJAX did more to enliven the web than any plugin had ever done previously, [sounding the death knell for Flash and similar technologies, R.I.P] and was the timely injection of functionality and responsiveness the web desperately needed. AJAX, however, despite its freedom from the page processing lifecycle, is still inherently tied to a page – its whole intent was to be able to refresh parts of a page without having to throw the whole page back to the server, so no matter how you implement it, Ajax is fundamentally tied to a page. Figure 1 is a good representation of the current state of web development, with different clients requiring dedicated applications to process information over the web

Figure 1 - The current state of web development

Web2
MVC changes how we even think about web processing by changing the url from pointing to a physical file sitting in a directory on a server somewhere to a call to a method in the code of our application. This is a huge change; the url doesn’t point to another page or image or even another site, it fires off functionality on demand.

Now, combine this url-based functionality with a robust client-side library such as jQuery, which is capable of consuming and populating services of various types, and you have the basis for a new processing model for web applications. Consider, free from the duty of page DOM processing, jQuery can intercept a click on the page and call any service we want instead. In this scenario, jQuery acts as a controller of our base page, synchronizing calls to a myriad of distributed lightweight service endpoints to deliver full functionality as a composite set. Incorporating the capabilities of HTML5, we’re free from supporting multiple plug-ins to support media, which we can also stream in from services as required.

So what’s really happening here is a combination of the extensibility of service oriented architecture (SOA) with AJAX-style web client processing for the purposes of delivering web applications as outlined in Figure 2.
 
Figure 2 - Composite Web Application Development

Web3

This model offers significant benefits over previous web development techniques including, but not limited to:

·         Extensibility: need a new feature? Build a new service and .js file to consume it. You’re done. And you can implement both to the live app without disruption of service.

·         Scalability: services can be provisioned collectively or separately to address performance concerns – which fits perfectly with modern virtualization practices.

·         Performance: by relieving the server from redundant page postback processing, and moving a large portion of processing onto the client, the server is free to dedicate more resources to handling dedicated lightweight service calls, significantly speeding overall responsiveness.

·         Maintainability: encapsulating functionality into independent services means if changes or added features are required by the application, only one service needs to be updated, not the entire application. And as it’s the service that will be altered in most cases, production environments will not have to be impacted by the service refresh.

·         Client Agnostic: Implementing this model frees processing from the page, meaning the same services which feed our web application can easily be consumed by a mobile or platform-specific client, extending the development effort in a parallel fashion.

Service based applications have been highly regarded for quite some time due to their clear separation of concerns and inherent benefits of such an implementation, but the challenge thus far in utilizing a Service Oriented Architecture with web applications has been the limitations of the page/postback processing model. Combining the capabilities of url-based method calls with AJAX-style lightweight service consumption, a composite web application model is emerging which will change the way web application development is considered and pursued. The revolution is coming.

Architectural Diary - Build a better FTP Drop Box

Monday, March 14, 2011 by Jonathan Taylor

The other day I was discussing the finer points of flat file conversion in Application Development (or lack thereof) with one of my colleagues on the Definition 6 Architecture team, and we got into a rather interesting conversation regarding how much of today’s data still gets transmitted via data documents of some kind. Modern programming practice is to transfer data via on-demand services, it's faster, easier, and in most cases much more secure. The truth of the world we live in is that most older systems, and an uncomfortably large number of new systems still  transmit data to business partners across the world using plain old text files filled with data in whatever standard they were supporting when the system was built. How's that for communcation planning? [Note: this practice has a name – Electronic Data Interchange, or EDI, and Microsoft has an exceptional tool for optimizing and synhcronizing these efforts, Biztalk 2010, but that's another post entirely – JT]

Now, my colleague, who shall remain nameless, pointed out that these systems have been functioning without problem for years, so something must be said for the persistence of such file transfer processes. My carefully worded retort was that this perceived stability was the direct result of poor sods like myself working my tail off to keep them going. At this point I feel it is my duty to disclose that while it doesn’t seem to have affected him personally, my colleague was once a long-time employee for an organization many would lay the finger of blame at for the creation and continued use of this file-based data transfer silliness, even in the face of more reliable, efficient alternatives (I won’t disclose the name of this much maligned organization, but it rhymes closely with "aye, be them"). And conceding to my colleagues’ point, this is surely the reasoning why these processes still exist today. (A clearer case of ‘if it ain’t broke, don’t fix it’ you’ll never find)

Thus, like them or not, we as developers are stuck with these processes, and it is up to us to implement solutions that accommodate them as best as possible. Now, a simply staggering majority of these systems rely on FTP transfer to distribute their data files, and typically it is up to the receiving party to pick up these files from an ftp "dropbox" and process them in a timely manner. FTP transfer has its own peculiarities that do not help this process, however, the most prominent of which being unpredictable transfer times and the disparity between the file arriving at the destination dropbox and the file completely downloading in its entirety from its origin. Aha! Herein lays our opportunity.

The problem of uncertain FTP delivery schedules causes file recipients to either delay retrieving the files from the dropbox until a time when they are certain the file will be there, "nightly file transfers," etc., or resort to "polling" to periodically spin up a process to look for the file being in the dropbox, and if it is, begin processing of the received file or pass it along to another process for further manipulation. These practices are inherently flawed and incur extensive overhead in time and system resources while constantly checking to see if the file has arrived, then locking resouceswhile the file finishes downloading before the processing of the files data can finally take place.

With .Ne however, these problems can be solved easily enough – if we can’t change the process, at least we can make it better, right? Let’s get started.

The key to our solution is a little-known member of the .NET System.IO namespace, the FileSystemWatcher class. The FileSystemWatcher does exactly what its name implies – it’s a lightweight object that monitors a directory and raises events to any changes that occur. We’re going to build a small console application and use a FileSystemWatcher to monitor our ftp directory for any new files that get created. Code Segment 1 details our System.IO.FileSystemWatcher implementation.

Code Segment 1

class Program

    {

        static void Main(string[] args)

        {

            //This should be an actual ftp directory path,

     //preferably from an App.Config file      

            String ftpPath = "path-to-ftp-directory";

 

            //Our watcher! 

            FileSystemWatcher watcher = new FileSystemWatcher(ftpPath);

 

            // Add event handlers for file created event

            watcher.Created += new FileSystemEventHandler(OnCreated);

 

            //Begin watching.

     //you need to set this to enable the FileSystemWater to raise events

            watcher.EnableRaisingEvents = true;

 

            // Code to shutdown the console if the user hits 'q'

            Console.WriteLine("Press 'q' to quit the sample.");

            while (Console.Read() != 'q') ;

        }

 

 

Right, so pretty straight-forward so far, a simple console app in which we setup the directory to be watched, implement a new instance of the FileSystemWatcher class then enable it to raise events whenever anything occurs in that directory. Now, the event we’re clearly interested in here is the Created event, which will fire every time a new ftp transfer arrives in our directory. To react to this Created event we wire up an instance of the FileSystemEventHandler to the watcher’s created event and point it to our method OnCreated, which is outlined in Segment 2.

Code Segment 2

        // Define the event handler

        private static void OnCreated(object source, FileSystemEventArgs e)

        {

            // write file name and arrival time out to the console when new files arrive

            StringBuilder sb = new StringBuilder();

 

            sb.Append("File: ");

            sb.Append(e.FullPath);

            sb.Append(" arrived @");

            sb.Append(DateTime.Now.ToShortTimeString());

            sb.Append(". Processing...");

 

            Console.WriteLine(sb.ToString());

 

            //now route the file to where it needs to go.

            ProcessFile(e.FullPath);           

        }

 

Again, fairly straight-forward, the OnCreated method simply reacts to the watcher’s Created event, and allows us to kick off whatever further processing we need to, namely writing out to the console the name and arrival time of the new file, then handing the file off to another method for further processing. Notice the FileSystemEventArgs object in the OnCreated method’s signature – we need to implement this class in order to capture the event, but it also allows us to work with a number of key parameters regarding the watcher.Created event, in particular the e.FullPath property which we’ll use to programmatically work with the newly arrived ftp file. The ProcessFile method is outlined in Segment 3.

Code Segment 3

private static void ProcessFile(String filepath)

    {

        FileInfo file = new FileInfo(filepath);

       

        //Switch to handle different file types

        switch (file.Extension)

        {

            case "txt":                   

                //process text logic here

                break;

 

            case "xml":

                //process xml logic here

                break;

 

            case "csv":

                //process csv logic here

                break;

 

                default:

                    break;

 

            }

 

Ok, so this is the final piece of our solution; we want our console app to be running constantly on our ftp server to watch our ftp dropbox at all times, so we need to be sure it’s as lightweight as possible and doesn’t maintain any internal state whatsoever, otherwise we’re adding extra load to our ftp server, and that’s entirely against what we set out to do in the first place, isn't it?. So let’s not do that.

The ProcessFile method is our routing method to move the file or notify any further services down the line that the file has arrived [an exceptional opportunity to implement the .NET Event Pattern, discussed in my previous post - JT]. We declare a FileInfo class to derive the extension of the file and route the file to a final destination based on file type.  By doing so, our console app never opens the file, never reads it into memory or maintains anything that would drain resources away from our server’s memory or processing pool, so it can run quietly alongside the rest of the server’s workload catching every new file that arrives in our FTP directory, and routing them to their final destination.

Ooo, Aahh.

Now, as simple as this solution is, we need to recognize what this implementation saves us – every time a typical FTP polling process started up, it would need to first gain access to the FTP directory, declare the directory reference in memory, then enumerate all the child directories (even if there weren’t any) followed by enumerating all the files contained in the directory to check if the file the batch process is looking for is there, and because the file transfer cannot be guaranteed to arrive at a specified time, the process would have to execute repeatedly until the file was finally found. Our FileSystemWatcher class, on the other hand simply responds to events that occur within the FTP dropbox, consuming substantially less resources.

So the key for gracefully processing FTP files without having to wait for the entire file to arrive is to process the file asynchronously. Doing so allows the main program to continue receiving file processing requests without having to wait for the code that actually processes the file. .NET provides a number of different avenues to finish that thought with, particularly in .NET 4.0, but that’s a bigger topic I’ll save for a later post. (Oh yes I did)

So to recap, yes we still have to deal with flat file transfers, but at least we can do so in a better manner, can’t we? Oh yes we can.


Architectural Diary - The .NET Observer Pattern

Tuesday, March 8, 2011 by Jonathan Taylor

Web application development can get tricky. Not only are we, as developers, charged with constructing brilliant websites that address every requirement each project entails, we also have to be concerned with the things not explicitly listed in our requirements document - things like how do we secure it? How do we know it's working at peak performance? How can we make sure people are entering in the data they're supposed to? On top of all that, if we're doing business website development, be sure to stay abreast of current application development technologies, the best ways to improve search engine optimization and last but not least, be sure to address brand experience strategy in everything you do.

See? Tricky. Fortunately, developers are weird. We like the challenges each web application development project presents. Really. We're weird.

Now despite this apparent quirkiness, in any software project we're working on, if there's something someone's built before that can help speed the development process along, we're likely going to use it. Design patterns represent tried and true ways to accomplish certain tasks in code - they're structures that solve problems common to many different project types. Confronted by a massive project with a tight deadline? Spot a process that can be handled by a design pattern? Sign me up! Design patterns to the rescue.

One of the most common design patterns which has been implemented time and time again is the Observer pattern, which is basically a structure that allows you to setup one or more entities (the observers) that react to changes in another entity (the subject). Not an uncommon scenario, right? Think RSS news readers that display news items as they are posted on the remote server. The observer pattern has solid grounding in real-world scenarios too; think of the iconic "hot doughnuts now" sign from your doughnut shop of choice – they light it up, people come running. Ok, maybe not the best of examples, as people still have the choice to grab a doughnut or not, but hey, it’s a vice, what can I say?

Traditionally the Observer pattern is implemented by using a set of objects derived from a common set of interfaces, namely the IObserver interface for objects we want to be notified of changes in another object, and the ISubject interface for the object we want to be watched. Basically, the ISubject interface defines a set of public methods to manage observer signup and notifications as outlined in code segment 1:

Segment 1

    interface ISubject

    {

        public List<IObserver> RegisteredObservers { get; set; }

        public Boolean state { get; set; }

       

        public void RegisterObserver(IObserver observer)

        {

            RegisteredObservers.Add(observer);

        }

 

        public void RemoveObserver(IObserver observer)

        {

            RegisteredObservers.Remove(observer);

        }

 

        public void UpdateRegisteredObservers()

        {

            foreach(IObserver observer in RegisteredObservers)

            {

                observer.Update(state)

            }

        }

 

So a set of methods to add and remove any objects derived from the IObserver interface to an internal list of IObserver objects which is used in the Update method to notify the observers of any change to the ISubject object, in this case a simple Boolean field called state (ugh, brutally obvious, I realize, but prudent..) . The observer objects implement their own interface outlined in segment 2:

Segment 2

    interface IObserver

    {

        public void Update(Boolean state)

        {

            //update status to reflect change in subject

        }

    }

 

And as expected, IObserver contains just one method to update itself to reflect any change in the subject object.

Not so difficult, right? A handy mechanism to handle distributed subscriber-based notifications for a number of different circumstances; if you haven’t found yourself in a situation where you needed to distribute multiple updates based off one event, trust me you will, and you’ll be happy you know about your friendly neighborhood Observer Pattern

Now while you are more than welcome to implement the Observer pattern using this traditional dual-interface manner, in .NET, there really is a better way. (You knew I was getting to it at some point, didn’t you?) Because the Observer pattern is so heavily entrenched in object-oriented development these days, and since the maintenance of registered observers can get pretty tricky pretty quickly in a traditional Observer pattern implementation, Microsoft went ahead and built its own short-hand version directly into the C# language from the very first version (yup, C# 1.0, don’t see that much anymore do you?) through the simple use of events and delegates. Microsoft uses it so much in their own internal coding, they even went so far as to rename it the Event Pattern (Oooo, Aaahh..)

OK, so here’s how it’s done: we’re going to build a subject class to expose an event whenever it changes internally, then we’re going to define a delegate to handle that event, which we’ll use to link all our observers to the subject– and we’ll transmit the subject’s change in state through a custom EventArgs class. Now, if that sounds like a lot, don’t freak out just yet, if you’ve ever wired up code to an event in .net, you’re already well acquainted with how events and delegates work through the standard signature of an event handler – think of a button click event handler like the one outlined in code segment 3.

Segment 3

public void Button1_Click(Object sender, EventArgs e)
{
    //button event code goes here
}

See that EventArgs parameter? That’s how .Net passes parameter values to event processors. So the cornerstone of implementing our own .net observer is by overriding the default System.EventArgs class with our own version to hold the information we need to pass to our observers from our subject class. Sound like a plan? Let’s get started.

Code Segment 4 lists a custom event class which contains two readonly properties, oldvalue and newvalue – we’ll use this class to notify all our observer objects whenever there’s a change in our Subject’s values.

Segment 4

public class SubectChangedEventArgs : EventArgs

    {

        //these values will hold values our observers want to know about

        private readonly int oldvalue;

        private readonly int newvalue;

 

        //constructor that sets old & new values

        public SubectChangedEventArgs(int oldval, int newval)

        {

            oldvalue = oldval;

            newvalue = newval;

        }

 

        //readonly properties to return Subject values

        public int OldValue { get { return oldvalue; } }

        public int NewValue { get { return newvalue; } }

    }

 

Ok, so now that we have a custom EventArgs class, we need to declare the event handler which our observers will mimic to receive subject change events – our delegate:

Segment 5

 

public delegate void SubjectChangedEventHandler(Object sender, SubectChangedEventArgs e);

 

 

The SubjectChangedEvenHandler defines a method signature which all our observers will implement to receive notifications from our subject; two parameters are defined – an object and an instance of our SubjectChangedEventArgs. When declared as a method in one of our observer classes, the object parameter will be a reference to the Subject object the Observer is watching, and changes to its values will be held in our readonly SubjectChangedEventArgs class; code segment 6 lists a typical observer object implementation.

Segment 6

    public class SubjectObserver

    {

        //int to list change in value

        int change;

 

       //subject change even handler to match our delegate and use our custome EventArgs class

        public void SubjectChange(Object sender, SubectChangedEventArgs e)

        {

            change = e.NewValue - e.OldValue;

        }

       

        //constructor that requires a subject to observe

        public SubjectObserver(Subject s)

        {

            //Register our delegate-based method to the subject instance

            //This is how we link our observers to the subject

            s.SubjectChanged += this.SubjectChange;

        }

    }

 

So, the SubjectObserver class has one method that matches our delegate defined to handle any changes in the subject, and we wire up the observer to the subject by linking our delegate-based SubjectChange method to our subject’s ‘SubjectChanged’ event as an event handler. Nice, huh? .Net baked-in goodness. The final piece of our puzzle is the Subject class itself. The Subject class has two responsibilities – to expose an event for changes to its internal value (which we’ll use to hook all our observers to as event handlers), and to ensure it raises this event any time a change to its internal value occurs. Code Segment 7 lists how our Subject class is structured.

Segment 7

public class Subject

    {

        //private int to hold the current subject's value

        private int subjectValue = 0;

 

        //public property to set the subject value,

        //the set method is where we capture the value change and

        //notify all the registered observers of the change

        public int SubjectValue

        {

            get { return subjectValue; }

 

            set

            {

                // new eventargs class to pass the current subjectValue and the new value

                SubjectChangedEventArgs e = new SubjectChangedEventArgs(subjectValue, value);

 

                //update the subjectValue

                subjectValue = value;

 

                //Signal all the observers

                OnSubjectChanged(e);

            }

        }

 

        //declare the event using our SubjectChangedEventHandler delegate

// to handle changes to the subjectValue

        //we'll also use this to attach our list of delegate-based observers to.

        public event SubjectChangedEventHandler SubjectChanged;

 

        //method to trigger our subject change event

        //Note: events can only be triggered from within their respective types,

        // thus we marked the scope as virtual protected to allow the method

        //to be over-ridden while still being able to raise the default event

        virtual protected void OnSubjectChanged(SubjectChangedEventArgs e)

        {

            SubjectChanged(this, e);

        }

    }

 

So there we have it, a public property with its setter calling a protected function to raise its own event to notify all our registered eventhandler observers. Any time the subject changes, the SubjectChanged event gets raised, and all our observers can react to the new value enclosed in our own custom SubjectChangedEventArgs class.

Now, admittedly that seems like a lot of work compared to the traditional ‘I only need two interfaces’ Observer pattern implementation, but the payoff is in the use of the pattern, as shown in Segment 8 which outlines the process of using the classes we detailed previously to gain our .Net Observer pattern sweetness.

Segment 8

    Subject subj = new Subject();

 

    SubjectObserver observer = new SubjectObserver(subj);

    SubjectObserver anotherObserver = new SubjectObserver(subj);

 

    subj.SubjectValue = 33;

 

    //both observer and anotherObserver both update immediately

    int observerValue = observer.Change;

    int anotherObserverValue = anotherObserver.Change;

 

Ok, now seriously, how freakin’ cool is that? No messy ‘I’m an observer, add me to the list of registered observers’ calls, no ‘ok, I’ve changed, let’s loop through the list of registered observers and let them know’ routines, just wicked fast event-based programming. And did I mention the wicked-fast-ness of this .net Observer implementation? Oh yeah.

Again this is a .Net-specific implementation of a widely recognized and utilized design pattern of modern object-oriented programming, the Observer Pattern. Microsoft uses this pattern extensively in their own class structure for the .Net framework – so much so, they’ve come to call it the Event Pattern. 

Oooh, Aaah…

Regardless, if you haven’t had the need to implement a similar pattern in your own coding projects, you probably will run into it sometime in the future, and when you do, you are now armed with the powerful and pervasive .Net Event Pattern.

 
The Content Marketing Platform Powered by Compendium  |  Sitemap