Showing posts with label lambda expression. Show all posts
Showing posts with label lambda expression. Show all posts

Thursday, February 02, 2012

Introducing conditional.js, a jquery plugin for clean predicate-action separation

These days javascript space is full of newly developed and emerging frameworks. It is still early to speculate which ones will make it and can become par to jquery's unique status, but some have already made it into quite a few production projects and are gaining momentum and popularity by the day.

Depending on your background - be it Open Source Java/Ruby/Python or Microsoft's .NET - examples could be different but one is the MVVM Framework for javascript - aka knockout. I have been and am a fan of all the possibilities this framework brings to the client-side code but sometimes all you need is a simple tool to organise your code and make it more readable - you do not need a full-fledged MVVM library.

Let's bring an example.

Consider we have a form where depending on the answer to one question, answering some other questions become mandatory. We have a form asking for our detail and if the answer to marital status from a dropdown is "married", then detail of the spouse needs to be provided.

If we were to build this in HTML/javascript, we would put the fields for spouse detail in a container and then hide/show based on the value selected from the dropdown.

Here we have a predicate: "whether marital status of married is selected" and we have an action which is "show or hide a container". Here the action is parameterised with a boolean which happens to be the return value of the predicate.


Coding this is almost trivial: use jquery (or plain old DOM events) to subscribe to changes of the dropdown value and hide/show accordingly. And none of that predicate/action nonsense!


But as the requirements gets more complex, the code gets more and more complex to the point where the intention of the code is buried underneath many lines of code. For example, what if the logic depends on the value of multiple fields? The complexity will increase exponentially with the number of fields involved. Also one common problems - those of you who have implemented such scenario would immediately remember - is that when the value is served by the server, the event is not triggered so the visibility of the container is not affected. For example, if we edit a saved form for a married person, server will send the HTML with the value of married status dropdown to "married", however, since the change event is not triggered, spouse detail container stays hidden. To combat this, we have to raise the change (or call the callback code) so that the logic is executed.

One solution is to use a framework such as knockout to wire the event with the logic as a client-side binding. One problem with such approach is that the binding to multiple fields is cumbersome, especially if they are involved in more than one such logic. Also, implementing custom action requires adding custom binding which is fine with one or two cases but not great when there are more custom action to be executed.

The solution conditional.js presents here is to a separation of predicate and action by:

  1. Subscribe to change events of one or multiple elements by providing one or more jquery selectors
  2. Accepting a predicate (a javascript callback function) that will receive the value of the elements
  3. A set of standard actions (hide/show and enable/disable) that will react to the value returned by the predicate. Alternatively registering a custom action, or simply just providing a callback action that will be called passing the return value of the predicate.

This probably sounds more complex than it is so let's bring the example - example above but this time with code.


        $("#spouseContainer").conditional({
            selectors: "#marst",
            predicate: function (maritalStatus) { return maritalStatus==="Married"; }
        });

As can be seen above, container with id of "spouseContainer" is used to start create the jquery object. We pass selectors (here a single string and it can be a string array too) that is for the marital status dropdown with id of "spouseContainer" and then a predicate defining our desirable condition which by default is visibility - i.e. whenever value of "marst" is equal to "Married", spouseContainer will be visible. Since we have passed a single selector, our predicate needs to accept a single parameter.

So I believe this 3 lines of code are really expressive and readable. This also take care of the problem of setting the status when the page is loaded with the desirable value.

In the next blog, I will delve into all options and possibilities of conditional.js.

Sunday, September 18, 2011

Performance comparison of .NET method calls

In this post I will try to compare performance of various method call types in .NET including IL's call, virtual call, reflection method call, delegates, compiled lambda expressions and Action/Func.

It is not too rare for me to pick up and say something about the internals of .NET framework or just general Microsoft stack only later to realise I was wrong - not in this case because I was wrong although that happens too but because things have changed since I last checked up or read upon them. This happens a lot on Stackoverflow where it is even more crucial to be right - don't wanna give false information to others.

With the advent of lambda expressions and introduction of generic delegates aka Action<T>, Func<T>, etc in .NET 3.0 things have certainly got funkier - pun intended! Now in .NET 4.0, we have the dynamic stuff which is even better, certainly solving many difficult problems we were facing in a statically typed environment. Best example is Simple.Data which I just love for its simplicity and would be impossible without it.

Now this is all well and good but it does come with a price tag - performance hit here - which we all know exists but its kinda like banking direct debit, you know you have set it up and it goes out of your pocket but since you do not see a bill, you do not realise how much you are paying. On the other hand, sometimes you might drop off the other end of spectrum and start micro-optimising by not using any reflection or dynamic hence loose the opportunity to make your code more maintainable by not using more expensive but much more elegant approach which involves dynamic or lambda expressions.

I remember from the old VB6 days when we were talking about late binding and how evil they were and we were to avoid them like plague. Now 10-12 years later and things have changed a lot: we are trying to solve much more complex problems and we need new tools and new languages hence the popularity of functional languages. On the other hand, our hardware have got noticeably better so what would be deemed to be a no-no back then, it has become commonplace to use. But I certainly see a new wave of awareness to the performance, thanks to the popularity of mobile and tablet platforms where memory and CPU just cannot be taken for granted.

Anyway, from whatever angle you look at it, it is useful to have a comparison.

I have created different scenarios where the same piece of code (which does a simple calculation) is called in a various ways. Here


As can be seen, calling DynamicInvoke on a delegate has the worst performance. Of notice, is relatively good performance of Dynamic objects compared to reflection.

In the next post we will discuss the detail and code for the test.