Over the weekend I had fun getting NServiceBus to publish events to the browser via SignalR. Both libraries are easy to work with; most time was spent learning Backbone and battling json serialisation of dates .

In the blotter demo, a view is bound to #commandForm. ModelBinding ensures a command is populated with the form inputs – providing similar binding to Knockout.

// Form controller
Labs.Form = (function (labs, backbone) {
    var form = {};

    // Model
    var command = backbone.Model.extend({
        url: "api/command"
    });

    // View
    var commandView = backbone.View.extend({
        el: "#commandForm",

        events: { "submit": "submitCommand" },

        initialize: function () {
            backbone.ModelBinding.bind(this);
        },

        submitCommand: function () {
            this.model.save();
        }
    });

    // Initialisers
    labs.addInitializer(function () {
        form.CommandView = new commandView({ model: new command() });
    });

    return form;
})(Labs, Backbone);

When the form is submitted a command is sent (PUT) to an ApiController which sends it on to the MessageBus. Quite nicely, Backbone PUTs new models and POSTs updated.

The CommandHandler simulates an aggregate root by handling the command and publishing an event every few seconds for a total of thirty.

public class CommandHandler : IHandleMessages<Command>
{
    public IBus Bus { get; set; }

    public void Handle(Command command)
    {
        Log.For(this).DebugFormat("Handling command - {0}".FormatWith(command));

        var raiseEventObservable = Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)).Timestamp();
        var stopObservable = Observable.Timer(TimeSpan.FromSeconds(30)).Timestamp();

        raiseEventObservable.TakeUntil(stopObservable).Subscribe(timestamped =>
        {
            var @event = new Event
            {
                Id = Guid.NewGuid(), AggregateId = command.AggregateId, Created = DateTime.UtcNow
            };

            Log.For(this).Debug("Publishing event - {0}".FormatWith(@event));
            Bus.Publish(@event);
        });
    }
}

RX is probably overkill here and more than likely incorrectly implemented.  However, I’m fascinated about the relationship between Event Sourcing, CEP and RX.  And I need the practice.

The web project subscribes to the events. Whenever an event is raised it forwards it on to all clients connected to the events hub.

public class EventHandler : IHandleMessages<Event>
{
    public void Handle(Event @event)
    {
        Log.For(this).Debug("Handling event - {0}".FormatWith(@event));

        var connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
        var clients = connectionManager.GetClients<Hubs.EventsHub>();

        clients.handle(@event);
    }
}

Thanks to the magic of SignalR and dynamic, server code invokes the ‘handle’ function on the events-hub proxy within the browser.

// Signalr client
Labs.Hub = (function (labs) {
    var hub = {};

    // Initialisers
    labs.addInitializer(function () {

        // Start signalr connection
        $.connection.hub.start();

        // Create events proxy
        var events = $.connection.events;

        // Handler for new event
        events.handle = function (event) {
            labs.vent.trigger("labs:hub:receivedEvent", event);
        };
    });

    return hub;
})(Labs);

Fiddler reveals that the client issued a long-poll get request when the application started. Whenever a message is dispatched from the server, this request ends and another starts. Given a better browser websockets would be used.

The Hub raises an ‘labs:hub:receivedEvent’ event along with the data from the server. The blotter handles the message – ensuring the Hub and the Blotter don’t have mixed responsibilities.  The Blotter adds the event to the eventCollection and renders it as a row within a table using a cached jquery template.


// Blotter controller
Labs.Blotter = (function (labs, backbone) {
    var blotter = {};

    // Models
    var event = backbone.Model.extend({});
    var eventCollection = backbone.Collection.extend({
        mode: event
    });

    // Display an individual event
    var eventView = labs.ItemView.extend({
        tagName: "tr",
        template: "#event-template"
    });

    // Display the list of events.
    var eventsView = labs.CollectionView.extend({
        el: "table",
        itemView: eventView
    });

    // Event handlers
    labs.vent.bind("labs:hub:receivedEvent", function (evt) {
        blotter.Events.add(evt);
    });

    // Initialisers
    labs.addInitializer(function () {
        blotter.Events = new eventCollection();
        blotter.EventsView = new eventsView({ collection: blotter.Events });
    });

    return blotter;
})(Labs, Backbone);

While the demo illustrates how easy it is to integrate these libraries, there are several issues that ought to be addressed:-

  • Functionally, a blotter should probably display events in reverse order and then only n-number of events. This should be quite trivial to implement with Backbone using the Comparator function on the eventCollection.
  • The lifetime of the events-hub proxy needs more consideration.  Should it really connect as soon as the application starts?  What should happen when an error occurs?
  • The commandView shouldn’t be responsible for saving its own model.  Instead it should raise an event that’s handled by a separate function.
  • The empty EventsHub feels like a smell.  Its sole purpose is to define an endpoint for clients and to allow the EventHandler to gain access to those clients.  SignalR’s PeristentConnection may overcome this as it provides more low-level control.
  • Despite using Json.NET SignalR does’t  provide a means to control json serialisation when using Hubs; adding a formatter to the global configuration had no effect .  Again, the PersistentConnection may improve things.

Do you feel guilty when you write code without tests, without test-driven-design? Are you shamed when only you can read your code, only you understand how a feature is implemented? Do you have a nagging feeling as you over-engineer a solution, when you find yourself writing a framework?

Or do you feel contented when you implement a feature with clean code, peaceful when you refactor the smelly? Are you quietly happy when your team finds it easy to read and extend your work, when you’re an anti-hero?

These feelings are driven by Developer Conscience, an inner feeling of right and wrong that drives our work.

Conscience derives from the latin word conscientia which means “with knowledge”. Religions typically believe that the “conscience [is]…linked to a morality inherent in all humans, to a to a beneficent universe and/or to divinity”. Seculars believe that our conscience is part of our genetic make-up, imprinted within us as part of our culture.

In Hindu, conscience is the…knowledge and understanding a soul aquires as a consequence of completion of karma over many lifetimes.

Buddha links…conscience to a pure heart and a calm, well-directed mind

As developers we can’t look towards divinity for direction, our conscience isn’t part of our DNA. Instead we read the books, blogs and tweets of people we respect. We attend community events where we talk to our peers. If we’re lucky we get to work with them.

Confucianism indicates that conscience….assists humans to follow The Way (Tao)…a mode of life for goodness and harmony

In Catholicism conscience is “a judgement of reason which at the appropriate moment enjoins [a person] to do good and to avoid evil”

Through continuous improvement we form principles, values and practices that are the basis of our professionalism and integrity. They help us write code, interact with our users, delivery value to our customers.

The Service Locator pattern abstracts the mechanics of creating objects. Rather than directly instantiating a dependency, an object asks a ServiceLocator for an implementation of an interface.

Consider the following legacy code.

    public class Client {
        public void Consume() {
            var service = new Service();
            service.Provide();
        }
    }

    public class Service {
        public void Provide() {
            //Implementation goes here
        }
    }

The Client instaniates an instance of Service and holds it within a method variable. There are no seams within this code. The Client is tightly coupled to the Service.

Now consider the following test-driven code.

    public class Client {
        private readonly IService service;

        public Client(IService service) {
            this.service = service;
        }

        public Client() : this(new Service()) {}

        public void Consume() {
            service.Provide();
        }
    }

    public interface IService {
        void Provide();
    }

    public class Service : IService {
        public void Provide() {
            //Implementation goes here
        }
    }

The Client now uses Poor Man’s Dependency Injection to instantiate and hold an implementation of IService within a class member variable. This pattern, often used during Test Driven Design, allows the Client to be exercised with a different implementation of IService. A test double can be injected into the Client to provide known behaviour and assert expectations. Despite this the Client remains coupled to the Service.

Finally, consider a simple implementation of the Service Locator pattern.

    public class Program {
        private static void Main(string[] args) {
            ServiceLocator.Register(new Service());

            var client = new Client();
            client.Consume();
        }
    }

    public static class ServiceLocator {
        private static readonly Dictionary<Type, object> services = new Dictionary<Type, object>();

        public static void Register<T>(T service) {
            services.Add(service.GetType(), service);
        }

        public static T Resolve<T>() {
            return (T) services[typeof (T)];
        }
    }

    public class Client {
        private readonly IService service;

        public Client(IService service) {
            this.service = service;
        }

        public Client() : this(ServiceLocator.Resolve<IService>()) {}

        public void Consume() {
            service.Provide();
        }
    }

    public interface IService {
        void Provide();
    }

    public class Service : IService {
        public void Provide() {
            //Implementation goes here
        }
    }

Rather than instaniating an instance of Service, the Client asks for an implementation of IService. The ServiceLocator is initialized with an instance of Service during application start up but it is easy to see how a different implementation could be introduced without affecting the Client. The Client and Service are now loosely coupled.

In reality, it’s unlikely that you’d use such a simple ServiceLocator. It’s more likely the ServiceLocator would be a facade in front of a Container that creates and manages objects with some degree of sophistication.

Service Locator Pattern separates instaniation from consumption. It encourages applications composed of loosely coupled components, introducing application-wide seams that allow us to change or extend the default implementation of certain services. It is rare that we really need an open-closed architecture, let alone a pluggable one. Better to keep things simple and refactor when necessary rather than over-engineer. However, the ability to strategically introduce stubs or mocks deep into a call stack to facilitate testing is a compelling reason to introduce the pattern.

Of course, the same is true of Dependency Injection. It is an elegant pattern that ensures coupling is kept to a minimum. All objects are given their dependencies rather than asking for them – facilitating testing at many levels. However, Dependency Injection isn’t something to be considered lightly. It is a pervasive pattern that requires a good understanding of object lifetime, often hard to integrate with frameworks that rely on reflection or configuration to instantiate objects.

In practice, the extra gain provided by Dependency Injection is often wasted. Applications rarely need the ability to substiute every object. Better to use pragmatic patterns to achieve the desired effect – especially when working with a legacy code base.

Service Locator Pattern is to components what Poor Man’s Dependency Injection is to classes. It allows us to raise the abstraction level of our tests, to thoroughly exercise an application without external dependencies or physical constraints, to write system or scenario tests.

As software developers we constantly look to other industries for inspiration. Some like to draw parallels with the construction industry while others look towards product development. It’s within our nature to analyze our processes, practices and principles in an attempt to increase the value of our work, reduce risks and improve quality.

At the moment Lean practices are very much in favor. We’re creating Kanban boards to model our processes. We’re keeping them lightweight and changing them as we see fit. We’re acknowledging that, as development teams, we need to limit our work in progress – that we’re most effective when we optimize the whole. We’re even beginning to estimate new work using actual data we’ve collected.

Where next will we learn our lessons? Logic would suggest a successful industry with a high risk and reward ought to provide some insights. Surely we can learn from the practices and processes of, for example, doctors, pilots, and chefs?

There are some great lessons, and some entertaining parallels, to be found within the martial arts. In particular, we can learn a lot from Bruce Lee. After many years of studying martial arts he came to learn that traditional techniques where too rigid and formal to be practical. Rather than dogmatically using one style of fighting he taught his students to constantly adapt and use different techniques to suite their individuals strengths and needs. Jeet Kune Do, the style he founded, teaches one to use simple and effective motions, to be flexible and to continuously study other forms.

Absorb what is useful; disregard that which is useless.

Be like water making its way through cracks. Do not be assertive, but adjust to the object, and you shall find a way round or through it.

Whereas most martial arts systems are considered products with a finite number of forms, JKD is considered to be a process. It provides guiding principles or ‘building blocks’ that enable personalized systems; no two students of JKD will have the same style.

Learn the principle, abide by the principle, and dissolve the principle. In short, enter a mold without being caged in it. Obey the principle without being bound by it. Learn, master and achieve.

It’s interesting that Bruce Lee soon realized his students would soon become obsessed with the name “Jeet Kune Do”, that they’d want to join an organization and become certified once it became mainstream.

I have not invented a “new style,” composite, modified or otherwise that is set within distinct form as apart from “this” method or “that” method. On the contrary, I hope to free my followers from clinging to styles, patterns, or molds. Remember that Jeet Kune Do is merely a name used.

To reach the masses, some sort of big organization (whether) domestic and foreign branch affiliation, is not necessary. To reach the growing number of students, some sort of pre-conformed set must be established as standards for the branch to follow. As a result all members will be conditioned according to the prescribed system. Many will probably end up as a prisoner of a systematized drill.

Jeet Kune Do is not an organized institution that one can be a member of. Either you understand or you don’t, and that is that…a Jeet Kune Do man who says Jeet Kune Do is exclusively Jeet Kune Do is simply not with it.

Poignant words of warning.

Follow

Get every new post delivered to your Inbox.