Tuesday, November 24, 2015

Command architecture and dependency injection

On a recent project, we were mapping commands to user intentions, covering all aspects pertaining to the usage of the application from the perspectives of the user and also recording them as the user journey continues during runtime. We decided that, in our architecture, commands will have the following features

  • Commands are pure Plain Old Objects
  • Commands are used to execute and capture user actions
  • Commands, when executed by a command handler, can run only in a single bounded context (a transaction boundary, with the exception of long running commands triggered via saga)
  • Commands are classes that implements ICommand Interface or possibly inherits from the BusinessCommand abstract classes
  • Command Handlers are registered by our Inversion of control in a central registry using the service locator pattern to load the needed command handler into the handling scope.
The above features are not everything that makes up a command, but enough to form my arguments around the subject matter. We concluded that we will leverage the dependency injection framework to serve as an invocation container for our commands and command handlers, therefore making for simple extensibility of the application by just registering a command (business requirements) and a command handler (business processor) using a declarative form rather than wiring everything up by hand whenever a new business requirements comes up, we can register and de-register our commands as the application evolve and due to clients need.

There is nothing new about maintaining a software architecture that favours plug-ability from ground up, I am a fan of software framework and architecture that makes writing code painless and developer friendly frameworks. Hence the reason for favouring service registration via declarative means over imperative paradigm.

I happen to chat with someone who disagree with using dependency injection as a way of service location strategy. We were chatting about how to create a console application like command line that takes in instructions like copy, move, ftp, message, delete etc ... At first the problem statement is something of high interests to me, and having been working on a distributed and message driven architecture for sometime now, I have come to appreciate the role of simulating the user actions, and my first go at the question is to use command pattern to capture all console instructions, and my suggestions was as follows:
  • copy becomes CopyCommand
  • move becomes MoveCommand
  • ftp becomes FTPCommand
  • message becomes MessageCommand
  • delete becomes DeleteCommand
With experience that I have gained from using and building lots of commands and handler in a very complex business oriented project, it should not be far fetched that command is the right answer to this friends question. I gave the suggestion of command pattern, it allows passing command message into each command after the parsing instructions entered into the console from the prompt using a text parser or scanner to finish the business of tokenization (my favourite). It is not that there are no other ways, but I am still sticking to my choice of pattern, which does the job gracefully (what you dont know doesnt kill).

Now the business of identifying what will form the basis of my friends architecture is over, my friend wants to know how I am now going to wire the commands from the console to the concrete commands declared as classes in the code base. I said to my friend that it is a piece of cake, use dependency injection as a service locator, as the application grows, it will just be a matter of registering a command against a particular naming convention, in our case the command will be registered against the name of the console command as the following example:

container.RegisterType("copy", typeof(CopyCommand));
container.RegisterType("move", typeof(MoveCommand));
container.RegisterType("delete", typeof(DeleteCommand));

The above registers console processing instruction against the command in code. A beautify way of locating commands that are mapped to the instructions, and of course I know that there are many ways that this can be done, but I preferred this approach .

Then my friend begin to see the clarity in my intentions, it was now occurring to him that I am building a software based on principles and pure object orientation and abstraction, but he continue to argue that my approach will break Single Responsibility Principle, but how? the command handles one thing, performs only one function. Also he criticised the use of the dependency injection for locating services, saying that the business requirements now relies on the IOC container to function appropriately, then I asked what can do this job than IOC container.

We ended the conversation by me suggesting other approaches to registering command against console instructions, and they are as follows:
  • Use reflection to locate relevant commands, by annotating the command classes with attributes that carries the console instruction name.
  • Create a registration repository class that does the wiring
  • Re-invent the dependency injection approach and give it a more shiny name to pretend it wasn't IOC.
  • Try and understand that we are both trying to decouple
While there might be little or no fault in the approach, but it is likely to succeed due to command pattern which would let you  organise your business requirements in a nice and self describing code structure (some code do speak for themselves, you do not need a huge documentation to figure that out).


Wednesday, January 21, 2015

JavaScript Journey Part 1 (Ninja Returns)

Today's application development is more focused on the web, we have experienced a shift in momentum from a typical desktop, dynamic website/web application to a more advanced web technologies that utilises HTML5, CSS3, Web components, advanced object oriented Java Scripting, AJAX and above all, Single page architecture. Complete evidence can be obtained from every nook and cranny of the web, cloud computing, mobile technologies and smart technologies. Coexisting applications is becoming the future focus, and to do this graciously, we must re-webify and take on the current mindset "The web is now becoming the desktop".

JavaScript is one of the oldest technology that refused to be replaced but instead, continue to get updated and deliver the modern day web, with its complementary technologies (CSS, HTML, XHTML, XML, XPATH), JavaScript is here to stay and to continue to drive forward our desire for very rich disconnected user experience over the web (GMail is a good testimony and the latest yahoo mail).

A not so long time ago, JavaScript was used by many, in its basic form. For form validation, browser navigation, cookie manipulation,  browser histories e.t.c Little did we know that JavaScript does have the potential and capabilities of solving the same complex problems that the modern object oriented compiled programming platform are solving. It is even  more better when the JavaScript V8 engine can run on the server, making JavaScript not just a browser based technology, but a server based technology too.

Single Page Architecture (SPA)
Web based application that runs as a single page but delivers the feel of a desktop over the cloud. This architecture does not favour the post back/refresh mechanism that was a dominant architectural standards sometime ago, though many developers are still doing this, including myself, because SPA is not a one solution fits all problem architecture. There are some real world problems that can only be solved by postbacks/refresh mechanism, in fact, the issues of standardising the W3C standards across all browsers (a.k.a Web components) even makes SPA architecture very difficult to work with, but there are ways around it, communities were formed and we have several OSS (Open source software's) that helps make life a better place to live in the world of SPA. See the below diagrams for the simple architecture cardboard for an SPA architecture.

Components of the single page 

Template engine: there are many available JavaScript template engines available as open source frameworks. They are responsible for rendering the templates which are part of the HTML or are computed as part of the HTML and JavaScript. A template engine would read the template based on known configuration patterns and if based on discover-ability architecture (software following a declarative pattern) would facilitate JavaScript views discovery. The template approach should not only define how data binding should be ensured or if a particular section is a single object binding or multiple object binding. Equally they should specify in the HTML data annotations for discovering a view, a data annotation for exposing triggers, events, handlers, a data annotation for model expression (regex). Will give full coverage of template engine later in other episodes of JavaScript. A good pseudo example of configuring an html section as a template and view is as follows:




 The pseudo template description above leverage's the web components custom element specification. A view is described as x-view with children which can be x-field (for describing fields for data-binding and/or rendering), x-association (for describing the association of inner views, for instance a customer view has multiple address views). More complex information will be given in the template engine section in other episode of this series ...

View engine:  based on the template that are described and pseudo example given above, the view object should be created as to, one view declaration to one view objects. I will give you further hints and approaches to the ways you can create a list view which only data-binds when you bind data, and a view object would be created for an list item when it is interacted with (giving us the power of lazy view object initialisation, and ability to bind 100s of data without worrying about how many views object's that will be created).

The view engine is responsible for the object oriented representation of the view template described in the template engine section. In fact a view object is a JavaScript object that can be described like so:


The framework would auto discover the view and would create an example view object like above.

Security context: a single architecture would require security to be built atop especially the type that assigns roles and responsibilities to the users based on allocation. So for instance, if user A can access a particular section of the SPA/form/view/x-field/associations the relevant security privileges will be allocated to the user. The security concept of an SPA would be to the granular level, security features can be added to views and parts of the view (called view policies). As of writing, there are no interesting security frameworks out there that can provide such level of granularity on the JavaScript side unless it is custom built. I have lead a particular SPA project where we built such rich security features, that it self is an episode on its own. A context object need to be readily available to be passed after a user login, this object would contain context aware information related to the current logged on user. An example is as follows:



above gives a skeletial view of what a typical security context object would contain. more details will be given later.

Observer model: View objects changes (field and association changes) need to be observed, a type called observer model is required, which tracks changes in a view object, as the view object changes, the observer  model changes. This kind of architecture can be traced back to the MVC (Model View Controller) GUI pattern. Fields themselves are observable, the views are observables and provides notifications to the observers or listeners. Also, property change notification can be implemented in the observer model, this will make the observer model to notify interested listeners to register and listen to when a model property changes. The concept of the property change notification makes the observer model observable too (two directional observations).


View Presenter: The presenter pattern is a architectural pattern that enables the events,  model binding and general house keeping functionality for the views. While the view is responsible for controls, rendering and input, the presenter will handle control events, register cross server events, listen to global/user context changes to notify the view. The presenter is where the developer concentrates his/her coding in this architectural style. Events will be handled, forwarded, dispacthed, propagated, delegated etc. The presenter is more concerned with separation of concerns and testability of the core functionality. Presenter is where the code gets interesting, but could become very ugly if all sorts of events and business functionality are handled in there (We need to watch the code-base).



if you go back to the pseudo template engine declaration, you will notice an attribute declaration within the x-view element, this declaration is to specify what presenter is need to be used against the view in question. Back to the presenter declaration above, there three life cycle methods (preInit, init, dispose), these events will be raised throughout some stages in the presenter lifetime. You will also notice the global getView and getEventBus function, they do the exact thing that the code describes. The getView gets the current view that was initialised with this presenter and the get eventBus gets the eventBus that is specifically made for this presenter. The eventBus can be used to listen to both presenter level events, view level events, cross presenter events and of course server sent events in case websockets are in use or the Server Send Events (SSE) is leveraged.

Lookin deeply into the presenter declaration, in the preInit life cycle method, you can get a good example of how view controls/fields events are registered. The example given registered changed event on the firstName field. Also the association added event was registered into when an address view is added, the event is fired.

Server side controller and actions or event web api: The wonderful thing about spa is, it is server side agnostic, it can consume data from different endpoints technologies, languages. It can in fact leverage COR (Cross Origin Request)  to pull data from different domains. We can leverage on the ASP.NET MVC view controllers for servicing the html s and the templates when requested by the spa page, and equally we can leverage on the  asp.net mvc web api for REST styled architectural data in json format.

Custom controls: the HTML controls cannot be enough, the HTML5 standard controls and functionality will not be enough to build a responsive SPA based architecture, jquery controls are too tied with jquery but can be abstracted into your spa architecture. You need to buy into the idea of custom controls, controls like tree view are not standard HTML controls, nice looking controls like auto complete are not standard controls, so you need the abilities to allow your development to introduce custom control as the requirement of your application gets bigger, or more so, if the same code are to be reusable across your architecture. see an example of custom control :



The control description above, describes a tree node structure. As you must have deduced from the type of the control that it is a "TreeControl", the name is the name that will be given to the instance of that control, note, a control can be a member of a view and some controls can allow for databing from the view observer model, of they are responsible for fetching their own data based on configurations sets. A nicer way to architect a control is to introduce an BaseControl which all other controls can inherit from using a prototypical inheritance of any form of JavaScript inheritance of your flavour.

This is just a quick peek spa architecture intro. I will be introducing more in dept blogs on other useful architectural approaches and patterns that can be used to fulfil the needs of spa.

to be continued ...