Flux – Unidirectional Data Flow Architecture

An overview of Flux Architecture

Unidirectional (as opposed to bidirectional) data flow can be thought of as both a solution for mitigating the downsides of an event-oriented MV* system in which events fly uncontrolled in all directions and a technique that provides proper support to ensure architectural separation between concerns. Flux is also about reactive programming and the capability of one system to inject additional behavior without having to add more conditional logic to its core – think of a portal application that acts like a pluggable system. Nevertheless, immutability plays an equally important role in this picture and should be always considered when working with Flux and React.

With popular MV* libraries today, views manipulate state, controllers manipulate state and models manipulate state. The difficult part in this case is to actually keep in sync all these states with the DOM and vice versa, especially when dealing with asynchronicity. Often times you’ll struggle with a combination of imperative DOM manipulation and templating code that will run because something directly or indirectly caused it.

Just think of the complexity of the mental model that you’ll have to deal with when working with a scenario that looks like this:


This is when Flux becomes handy:


Although the MV* and Flux diagrams might seem similar at a first look, there’s one key difference between them: in the Flux diagram the arrows point in a single direction closing the loop in a consistent cycle – so is not a matter of being simpler than MV*, but rather being less confusing and easier to read.

Flux consists of four major parts: the Dispatcher, the Action, the Store and the View (React component).
The flow goes like this: an user interaction (mouse click) or an external event (push notification) triggers an action which is dispatched by the central dispatcher to all the possible stores, which in turn notifies all the interested views that a change happened in the state. This goes especially well with React’s declarative programming style that simplifies the management of state transitioning inside the views.

The actions flow through the system one at a time, the Stores becomes the single source of truth in the application and the Dispatcher allows you to specify the order in which the Stores execute their logic. Flux also separates the concerns of receiving and sending data. All these small things contribute to the overall predictability of the system.

Flux libraries

Who said that diversity isn’t good? Is Model-View-Controller, Model-View-Presenter, Model-View-ViewModel, Model-View-Adapter, Presentation-Model and all their various implementation sounds familiar to you? Well, the same kind of thing happens with Flux: there’s a lot of libraries out there (Alt, Reflux, Fluxxor, Fluxible, Redux etc.) and a lot of nice features to choose from, but before commiting to any of these be sure to get yourself familiar with Facebook’s reference implementation https://github.com/facebook/flux/tree/master/examples as a starting point.

Wrap up

Flux can be seen as an alternative to MV*, since it „eschews MV* in favour of a unidirectional data flow”. However, Flux is not meant to be simpler than MV*, but rather was designed to keep your code clean and predictable. The versatility of this architecture is well recognized by many, including Twitter, Yahoo, Facebook,  Instagram, Aurelia etc. Use it whenever your application targets a medium to complex codebase.

ReactJS – functional reactive and declarative UI programming to the rescue

ReactJS is a JavaScript open-source library for creating user interfaces. It’s maintained by Facebook, Instagram and the open-source community. It can be tempting to think that ReactJS is just another JavaScript library that operates with the DOM, along with Angular, Aurelia, Ember or Polymer, but in reality it addresses a wider spectrum of edge cases, not just web applications: native development (iOS and Android), TV interfaces (Netflix), non-browser environment (server-side rendering), canvas graphics with video-like smoothness and others. What this means is that instead of ReactJS talking only to the DOM API, it just as well can be communicating with the Graphics Layers or WebGL – good old computer graphics programming.

ReactJS rendering layers

So basically ReactJS  is just a generic component model working for a lot of programming models and is going beyond the borders of W3C WebComponents and web applications, towards native iOS or Android development or even rendering directly with WebGL for complex 3D scenarios. The beauty of it is that you only need JavaScript to achieve this.
“You can think of ReactJS as a small library orbiting around the DOM. However as ReactJS is integrating with more and more things, the picture kind of flips around” (credits to Sebastian Markbåge):

ReactJS Integration

We all know that working directly with the DOM is slow. Because performance is crucial, one of ReactJS’s foundation stones is the Virtual DOM which makes the server-side rendering possible and allows re-rendering the entire UI every time the data changes without being prohibitively expensive. This means that ReactJS apps can easily run at 60fps even on mobile devices. Behind the scenes, the Virtual DOM relies on an efficient diffing algorithm that compute the minimal set of DOM mutations before actually touching it. The diffing engine works kind of the same way as the one used by the source repositories to stores the different revisions of a source file. Remember: whenever applicable, an algorithm will always find the best solution, whereas a human is prone to making errors.

Another important aspect of ReactJS is how it keeps the model in sync with the UI. With the traditional imperative programming paradigm, the way that you would normally handle this would be to initially render the markup at time = 0 and then manually sync its representation every time a change occurs in the model (time = 1, time = 2 etc.). For example, if you are using only jQuery to do the updates, the code quickly becomes spaghetti. With ReactJS you declaratively describe the UI at any point in time, not just the initial render, and let the view do all the required mutations when needed. It’s that simple: whenever there’s a change in the state, the entire thing is re-rendered. This is called one-way reactive data flow and will see how well it fits with everything else, especially with Flux, in some other article.

Speaking about programming paradigms, functional programming becomes a first-class citizen with ReactJS  not only in theory but also in practice, which means that the components are represented as idempotent and composable functions. The tree-like data structure resulted in the diffing process between two subsequent function calls will be transparently translated into a list of DOM mutation operations which ultimately will be reflected into the DOM. This is a big leap toward transforming theoretical functional programming concepts into actual code.

Debugging in Node.js under Windows

In order to debug a node.js server, you only need the node-inspector debugger package.
To install it, run the following command:

npm install node-inspector

Suppose that after installation you have the following directory structure:

C:\Program Files\nodejs
| +---node-inspector
| | +---bin
| | | +---inspector.js

In command prompt, go to the root folder of node.js, and type the following command:

C:\Program Files\nodejs>node node_modules\node-inspector\bin\inspector.js

Now, open another command prompt and go to the root folder of your node.js project, and type the following command:

C:\Program Files\nodejs\Workspace\MyProject\src>node --debug index.js

Everything is set and done now. To start debugging, open in one browser tab the following URL http://localhost:8080/debug?port=5858 and in another tab go to your project’s URL.

In the first tab you can navigate through your project’s source files, set breakpoints, run step by step, view the call stack etc. just like you would normally debug a client js file.

Have fun!

Prototypal inheritance in JavaScript

Is JavaScript an Object-Oriented Programming language? Does JavaScript support inheritance? Believe it or not, these are some tough questions that stir up endless discussions.

As in W3Schools.org, “JavaScript is THE scripting language of the Web” On Wikipedia, JavaScript is characterized as “a prototype-based scripting language that is dynamic, weakly typed, general purpose programming language and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles”.

However, form my point of view, if JavaScript supports object-oriented programming style, doesn’t mean that is an object-oriented programming language, at least not in the way that Java/C#/PHP 5+ is! I think that “JavaScript is an object-based language” is more realistic and closer to truth. However, one of the main characteristics of an OOP language is inheritance, which by the way is supported in JavaScript through prototyping.

Let’s see on code how we can achieve inheritance in JavaScript. First of all, let’s consider a “class constructor” called Human which could act as a base class:

function Human() {};

Since Human is a Function object (everything in JS is an object, even the Function!), it can have properties like “prototype”. In this moment, the prototype property of Human has an automated property called “constructor” which points to itself (to Human function).
If you try to debug this line of code with the Developer Tools from Chrome, you will have the following results:

Property ===> Expected result
DEBUG: Human.prototype ===> Human {}
DEBUG: Human.hasOwnProperty(‘prototype’) ===> true
DEBUG: Human.prototype.constructor ===> Human ()
DEBUG: Human.hasOwnProperty(‘constructor’) ===> false
DEBUG: Human.prototype.hasOwnProperty(‘constructor’) ===> true
DEBUG: typeof Human ===> ‘function’
DEBUG: Human instanceof Function ===> true
DEBUG: Object.getPrototypeOf(Human.prototype) ===> Object {}
DEBUG: Object.getPrototypeOf(Human.prototype) === Object.prototype ===> true

When an object is constructed, that object gets an implicit reference to the value of the constructor’s prototype property, which is an object. “Implicit reference” means an internal thing, not some property of the object. The implicit reference is hidden away, but it can be extracted with Object.getPrototypeOf(). E.g. When we write function Human() {}, Human has a new object constructed called prototype which “gets an implicit reference to the value of the constructor’s prototype property (Object.prototype)”. The “constructor’s prototype property” is finally an object (the base of all the things in JavaScript).

Property ===> Expected result
DEBUG: Object.getPrototypeOf(Human.prototype).constructor === Object ===> true
DEBUG: Object.prototype ===> Object {}

Next, consider the following line of code:

Human.prototype = {
  name : 'John'

After this line of code, the prototype will become a simple object, and because of poor JavaScript design, the prototype’s constructor property will point to Object (). That’s because the constructor property is no longer part of the Human.prototype, but rather of Object.prototype (if the property isn’t found in the prototype object, it is looked for in the prototype object’s prototype).

Property ===> Expected result
DEBUG: Human.prototype ===> Object { name : ‘John’}
DEBUG: Human.prototype.constructor ===> Object ()
DEBUG: Human.prototype.hasOwnProperty(‘constructor’) ===> false

Human.prototype.color = 'white';
Human.prototype.getName = function() {
  return this.name;
Human.prototype.getColor = function() {
  return this.color;

After these lines of code, the prototype will become Object { name : ‘John’, color : ‘white’, getName : function() { return this.name }, getColor : function() { return this.color } }
And now for the “object instantiation”:

var h = new Human();

Also the poor design of JavaScript is further reflected when instantiating the object h. That is, the contructor is not taken from Human.prototype, because as previously mentioned, the prototype of Human is a simple object with no automated constructor property and that’s why the constructor is taken from one level up which is from Object.prototype.

Property ===> Expected result
DEBUG: h.constructor ===> Object ()
DEBUG: Object.getPrototypeOf(h) ===> Object {
name : ‘John’,
color : ‘white’,
getName : function() {
return this.name;
getColor : function() {
return this.color;
} }
DEBUG: typeof Object.getPrototypeOf(h) ===> ‘object’
DEBUG: typeof h ===> ‘object’

To “patch” JavaScript’s poor design, we will create the constructor property which points to itself (to Human)

Human.prototype.constructor = Human;

Property ===> Expected result
DEBUG: Human.prototype ===> Human {
name : ‘John’,
color : ‘white’,
getName : function() {
return this.name;
}, getColor : function() {
return this.color;
DEBUG: Human.prototype.constructor ===> Human ()
DEBUG: Human.prototype.hasOwnProperty(‘constructor’) ===> true
DEBUG: h.constructor ===> Human ()
DEBUG: Object.getPrototypeOf(h) ===> Human {
name : ‘John’,
color : ‘white’,
getName : function() {
return this.name;
getColor : function() {
return this.color;

And now for the child class, which in our example will be called SuperHuman:

function SuperHuman(superpower) {
  this.superpower = superpower;
SuperHuman.prototype = new Human(); // inherit from Human
SuperHuman.prototype.getSuperpower = function() {
  return this.superpower;
var sh = new SuperHuman('laser');
SuperHuman.prototype.constructor = SuperHuman;

If you have the curiosity to debug the code and check the state of the properties after each line of code, you will see that SuperHuman will behave in the exact same way as Human did – that’s because SuperHuman inerits from Human and therewith all the design problems that we encountered before.

See ya!

HTML5 Websockets, Node.js And Socket.io On Windows

Assuming that you already Googled around for the terms “HTML5 WebSockets”, “node.js” and “socket.io” and you came to the point where you wanted to actually test it a bit, you can follow the steps below so that you can create the magic with your own hands.

“The server side”
What do you need to do in order to run your first WebSockets server on Windows:
– go to http://nodejs.org, download and install it
– in command prompt, go to C:\Program Files\nodejs and run the following command:

npm install socket.io

– under C:\Program Files\nodejs create a new file named server.js with the following content:

var http = require('http');
var io = require('socket.io');
var server = http.createServer(function(request, response) {
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.end('WebSocket server is up and running!');
var socket = io.listen(server).set('log level', 1);
//Listeners for intercepting client messages
socket.on('connection', function(client) {
    client.on('message', function(data) {
        console.log('Message from client: ', data);
    client.on('customMessage', function (data) {
        console.log('Custom message from client: ', data);
        var now = new Date().getTime();
        //Emits back to the client a message
        client.emit('customMessageResponse', data + '->' + now);
        //Broadcasts to all the clients a message
        client.broadcast.emit('customMessageResponse', data + '(broadcasted)->' + now);
    client.on('disconnect', function(){
        console.log('Client disconnected');

– in command prompt run the following command:

node server.js

– voila! the server is up and running
So far so good with the server side. But what about the client side?

“The client side”
– download a test HTML file from here http://goo.gl/9ul1O
– allow the file to be served by your favorite web server (IIS, Apache etc.)
Now for the tests!

“The magic”
– go to http://localhost/downloaded_html_file.html (for demonstration purposes, I will open it in 3 separate browser instances)
– almost instantly you should see the message “Client connected to the Server!”
– type something in the first input box, click on “Send Message!” and you should see the message in the WebSockets server log window, just like in the image below:

– now let’s test the broadcast functionality of the WebSocket – type something in the second input box, click on “Send CustomMessage!” and you should not only see the message in the WebSockets server log window but also in the 3 separate browser instances:

– if you’re curious to inspect the HTTP traffic (through Fiddler for example), you can see that in order to establish a WebSocket connection, the HTTP connection must be upgraded to a WebSocket connection (HTTP/1.1 101 Switching Protocols)

– unfortunately Fiddler logs the client-server communication in a way that’s a bit messy

PHP multithreading through .NET interop

Is PHP supporting multithreading? The answer is NO, if you are excluding the interop mechanism.
First of all, let me tell you a story about Threading: a CPU can have one or multiple cores. Each core can have one or multiple processes spawned by applications which in turn can be forked with child processes. Each process / child process can have one or multiple threads which are “the smallest unit of processing that can be scheduled by an operating system” (Wikipedia). Further down, Microsoft comes with a concept of task, which is included in the latest version of the .NET Framework – Parallel Framework (PFX).

For Unix we have http://www.php.net/manual/en/intro.posix.php and http://www.php.net/manual/en/intro.pcntl.php which are a set of complementary libraries that allows process manipulation operations. Let me repeat that: “process manipulation operations”… since there is nothing mentioned about threading, you can simply put it this way: PHP doesn’t natively support threading in Unix through the libraries mentioned above, but rather it supports process forking. As you may already noticed, I used the term of “natively” because you can achive multithreading by interoping with languages like Java, C / C++ or even .NET through Mono. If you wonder what are the advantages of using threads over processes in general, read this http://www.programmerinterview.com/index.php/operating-systems/thread-vs-process/; in particular, each language can have it’s own mechanisms of dealing with threads. A nice article on “multithreading” in PHP can be found on my comrade’s blog Tudor a.k.a. motanelu http://blog.motane.lu/2009/01/02/multithreading-in-php/.

Since posix and pcntl libraries are not supported on Windows, I’m going to assume that some of you who are running PHP under Apache / IIS on Windows will still want at some point to multithread the application. Have no fear, .NET is here! If you are familiar with C#, VB.NET or maybe F#, you can easily take advantage of the interoperability between PHP and .NET through the DOTNET class http://www.php.net/manual/en/class.dotnet.php and with it of all the goodies that the .NET Framework 4.0 is made of: PLINQ, Parallel class, task parallelism, concurrent collections and other. Make no mistake, as I already mentioned, the interop mechanism can be also used from Unix in pair with some languages, but since I primarily am a .NET programmer, I’m going to explain this through C# code.

I will assume that you have installed at least Visual C# 2010 Express Edition. First create a new Class Library project: File -> New Project -> Class Library. We’re going to call it MultithreadedDotNetClass. The purpose of this library is to add random numbers from multiple threads, avoiding duplicates. I will attach the source code here http://goo.gl/1so4v

In order to install the new assembly in the GAC, so that we could use it with the DOTNET PHP class, we need to sign it with a strong name. You can either do this from the IDE or with the SN tool from the .NET SDK. I will do this from the IDE, by going to Project -> MultithreadedDotNetClass Properties… -> Signing -> Sign the assembly.

Before building the library, I will make this assembly visible to COM components by setting the [assembly: ComVisible()] attribute to true (by default is false). Now you can finally build it.
Now let’s install our assembly in the GAC. Open a new command prompt, go to the location where gacutil is installed and type the following:

gacutil -I "C:\Path\To\The\Library\MultithreadedDotNetClass.dll"

For the test create a new PHP file, test.php, with the following content, replacing the Version / PublicKeyToken with your own:

$multithreadedDotNetObject = new DOTNET('MultithreadedDotNetClass, Version=, Culture=neutral, PublicKeyToken=b9137eaca16ad247', 'MultithreadedDotNetClass.Program');

If you have trouble in finding the Version / PublicKeyToken for the MultithreadedDotNetClass assembly, type this in the command prompt:

gacutil /lr MultithreadedDotNetClass

The result will be the Strong Name of the assembly:

After running our test, the output is as expected:

Have fun!

Between Adjacency List Model and Nested Set Model

There is a time in your project when you need to represent some hierarchical data in the database and it happens to use MySQL – and not MSSQL – which BTW supports recursive CTEs and recursive functions.
Now, there is a simple and easy way to represent the hierarchical data, which is fast at insert/update operations and slow at select operations (recursion bleah!). Let’s take a look at its structure:

name    VARCHAR(50), NOT NULL
parent  INT, NULL

..and there is the opposite of the first solution (no recursion, fast select):

name    VARCHAR(50), NOT NULL

I will focus on the second approach, and just to be sure you get the idea, I will attach an image representing some hierarchical data that we’ll be able to query:

The blue text represents the depth of the category and the red text represents the lft and rgt database fields. The green text represents the number of products in the category. You’ll see that if “Portable electronics” has 4 products, the sum of it’s child categories must be equal to 4 (“MP3 Players” + “Flash” + “CD Players” + “2-Way Radios”).
Before choosing between the two approaches, you should be aware of the complexity of the queries and the conditions for the CRUD operations. Below you can find some examples :
– update condition, when moving a category in another category (PHP syntax):

– select statement for categories and number of products (MySQL sytanx):

rgt = lft + 1
AND id = parent.id
)AS is_leaf,
(COUNT(parent_sub. NAME) - 1)
categories AS node_sub,
categories AS parent_sub
node_sub.lft BETWEEN parent_sub.lft
AND parent_sub.rgt
AND node_sub.id = parent.id
)AS depth,
COUNT(products.id)AS products_count
CROSS JOIN .`categories` AS `parent`
INNER JOIN .`products`
INNER JOIN `categories_products` ON products.id = categories_products.product_id
categories.lft BETWEEN parent.lft
AND parent.rgt
categories.id = categories_products.category_id
AND(categories.store_id = 1)
`parent`.`lft` ASC

and the result..

…and if you want to wrap it nicely in a tree-like HTML control, you could end up having something like this:

Happy coding!