My code has ADD

Things that interest me in the field of computing. My focus will be mostly in Java, JavaScript and Scala.

Saturday, May 3, 2014

You must have watched diving or synchronized swimming or a number of other sports, at least during an international sporting event like the Olympics. Then you must have felt like wow that particular athlete was great. When it comes to scoring, you often find that you had no clue of who was going to win.
Having a gut feeling for quality of your code could also be misleading. As a technocrat you need to quantify quality. You need to talk in terms of measurable entities. There are various metrics that can be evaluated for code - cyclomatic complexitiy, Halstead measures, lines of code, etc.PlatoJs is a nice tool to visualize these measures on your project. Here is a snapshot:

In the above we see how broccoli has managed to make their files smaller over time. You can also drill down into individual files:

Here is a small shell script for getting reports using Plato on git repository:

Sunday, May 12, 2013

I remember writing JSP where the server would dynamically generate the content for a client. Today, we are still doing some of this at the server but as our web applications have started getting more sophisticated it has become imperative that we do more of this at the client. RequireJs text plugin is of great help for this. Similarly for a web application that is dynamic - it would be great if it were book-markable too.

While browsers do NOT send the '#' and the following string of a URL to the server (that would be a page-reload), most modern browsers will append the fragment to the redirected url. Now is this the right thing to do? It's at least not better than dropping the fragment. Why would it ever be bad in any ways? Answer: If the redirected page also interprets the fragment but in a different way? That would be an accidental collision of semantics.

Getting back to the question though, Chrome still does not open the email after I sign in! This is because the login page doesn't handle the window.hashchange event. If it did (e.g. called history.pushState()), the #fragment will be relayed to the next redirect too and we should be happy to see the email direcly.

Three pieces of advice -

Do not use hashchange event directly but instead use something like jQuery which can simulate hashchange events (by a polling mechanism) for browsers like IE7

Your sign-in page should relay hash fragments

If the sign-in page is NOT under your control - you are mostly out of luck. Let's see how we can defend agains that below.

We could encourage users to not share the URL they see in their address bar directly but instead provide a "SHARE" button, which would generate another URL that captures, as a query-string parameter, the same information that would otherwise be in the #fragment. E.g. http://myapp.com#mypage is converted to http://myapp.com?hash=mypage

Next you would write you app to interpret the "hash" parameter as the hash fragment. But is that good enough? What happens with a url like http://myapp.com?hash=mypage#mycontacts ? Obviously, the fragment must take precedence over the query string. (You see why?)

Wednesday, May 8, 2013

HTML5 is here but we got IE 8 to support and then IE 9 is gonna be around for a while too. Often times we might be generating data on the browser that the server is not aware of and need not be aware of, e.g. we might be drawing some doodles and we want to save it and keep a copy locally on our desktop. Now since the content is already here at the browser, why should we not be able to write to a file? Well that's why we have data uri (also see Data_URI_scheme)
But tragically, it doesn't work with most contemporary browsers. We could then use something like downloadify (uses flash though).
So, is there a javascript/html only solution? None so far that works perfectly (Data-uri on Safari and Firefox 19- requires the user to enter a filename and there is no default name support. On IE there is the document.execCommand that you could use but it require pop-up to be enabled and once again you can't suggest a default file name).
Well it might seem very dumb but sacrificing latency and server cpu cycles and just doing a round-trip to the server and using an anchor element seems to be the safest bet:

Wednesday, April 24, 2013

With the single-threaded nature of JavaScript, the use of callbacks is innate to it. Promises (e.g. jQuery Deferred) are a nicer standardized way of making asynchronous function calls while at the same time tying up dependencies between different async tasks (e.g. $.when(), Promise.then(), etc.).
In the examples I present here I will use jQuery Deferreds/Promises.[The difference in Deferred and Promise is the perspective. Deferred is from the perspective of the "producer", which will resolve or reject the deferred. While Promise is from the perspective of the "consumer", it attaches callbacks to the promise to be called upon failure or success. See jQuery Deffered]

The Problem

Most often we won't need to have multiple outstanding promises of the same type - e.g. let's say we have an input box for a search phrase and when one presses a submit button, the search phrase is submitted to a remote server and the result is displayed when the response comes back. Our code would look something like:

Now lets say you typed something and clicked the submit button. Then before the server responded, you edited the text and clicked submit again. What would happen?
Whatever response comes first will be displayed and then overwritten with the response that comes second. Note, can you assume that the responses will arrive in the same order as the requests? Usually, NOT.

Lets prevent multiple outstanding requests

So, how would you solve this? [If you are wondering why would this be a problem in the first place, maybe in a real application, we perform some expensive operations on the response.] How about disabling the submit button as soon as one clicks on it and enabling it when the response comes back?

The reason we re-enabled the button in the always callback instead of the done callback is because we want to re-enable the button in case of either success(done) or failure(fail), so instead of repeating it in those two callbacks, always gives us a convenient shortcut to stay DRY.

But why make the user wait?

But lets say we are not happy with having to WAIT for success/failure. If we like to search something else and don't care about the current ongoing search, what should we do?

We preempt the obsolete callbacks. But how?
Would a boolean flag work, as follows?

NO the above is no different than the previous example; since we haven't gained any more expressive power. The attribute disabled could be thought of as the equivalent of __preempt variable!
Actually, now it's worse. We allow the user to hit submit button multiple times but we display only the first result instead of the last.

While the above works, we are assuming that the responses come in the same order as the requests. If that is not the case, we might need to have the request (the search criterion) itself embedded in the response, which would enable us to place the related search phrase back in the input box whenever we receive a response. But chances are we cannot dictate the response payload (e.g. we don't control that server or it is shared by other consumers and we can't change the api).

Sunday, April 14, 2013

A functional programming language (e.g. Scala or SQL for that matter) encourages one to think in the problem domain and write solutions that are declarative and accurate (provably so indeed). However, that is usually a lie! After coming up with a solution, one then has to worry about performance and see how to tweak it. And to be able to do so one has to know how the language works - which contradicts the whole premise of being declarative in the first place.
With something like SQL, we have query optimizers and I believe they do a pretty good job.
Now the same could be true in a pure functional language like Haskell, which, is free to reorder all our expressions as long as the dependencies are maintained. However, with Scala, expressions are allowed to have side effects (of course one should strive to not have those) and thus in general reordering of expressions is something the compiler probably won't do for us. And thus we have (lazy) val v def.
E.g.

Sunday, March 17, 2013

I was working on a web application where a user would subscribe for ticket prices for air-fares. She would enter the source and the destination and get live updates to prices and options.
Now, every time she enters a new pair, a new panel/tile would be added to her page that started ticking. Those panels were persistent; she could logout and when she logged back in later, the panels would load and start the subscriptions anew.
The browsers we needed to support included IE8. We were using socket.io for making the requests and receiving subscriptions. But the library would fall back to using jsonp-long polling or xhr-streaming for instance. Now, as we know, IE limits the number of Http connections one can have to 6. This meant if we made too many requests concurrently, we would experience delays as the request would get queued up. This was the case when loading a page with numerous persisted panels.
We thus allowed a batched request API, a simple array, e.g.[ "NewYork-London, "NewYork-Paris", "NewYork-Jakarta" ]
It would be nicer to not have to differentiate between the user entering 3 individual pairs or a batched request being made on her behalf upon page load.
This is where setTimeout(..., 0) becomes useful. [Note: Underscore.js's _.defer() does the same]
You can look at the code in action at CLICK HERE

When a number of requests are made in a loop (that is in the same call stack), the FIRST subscribe() call schedules a call to flushSubscribe() to be made when the current stack unrolls (not exactly! See the bottom of this post). All subsequent subscribe() calls in the loop will NOT unroll the stack and thus simply modify the payload, namely pendingSubscribe.

Now, if you are wondering why we don't just prepare the batched request where we loop, it is because when you are using a framework like Backbone, you want to have a layered architecture and that might not be easy. In my case, the panel was designed to be editable and would issue its own request; consequently, it would be unaware of any batching strategy.

Note: setTimeout(fn, 0) simply puts the function fn in the event queue's front but after any other similar functions already scheduled with setTimeout(otherFn, 0). CLICK HERE FOR PROOF. This doesn't affect the batching logic above per se. However, if we had an unsubscribe() call associated with a button click - then we'd need to be a bit craftier; as we don't want to send an unsubscribe request BEFORE the corresponding subscribe request. If anyone needs help with that, drop me a comment and I can update this post with a more complete example. But in brief, the unsubscribe request would check if we already have a pendingSubscribe, if so simple do an "early cancellation", i.e. remove the pair from that array.

Wednesday, February 8, 2012

SLF4J has done a good job by allowing users to continue using whatever logging framework they are currently using and then in time move on to LogBack. I like the way they require the adapter jar (e.g. slf4j-jcl.jar or slf4j-log4j12.jar) to have the org.slf4j.impl.StaticLoggerBinder and a few other classes for static binding. And those classes are supposed to implement interfaces from the aptly named org.slf4j.spi package

I thought they would load that class via reflection (=dynamically bind) but looking at the code in org.slf4j.LoggerFactory, it is not the case:

StaticLoggerBinder.getSingleton().getLoggerFactory();

So that might suggest that when they packaged the slf4j-api.jar, they had either slf4j-simple.jar or slf4j-nop.jar in the classpath, however that would result in a circular dependency as ILoggerFactory interface that the above method returns is defined in slf4j-api.jar. So, I think when they packaged slf4j-api.jar, they have a stub implementation of StaicLoggerBinder (and other similar classes) but then remove the .class files from the jar. Sounds a bit unkosher, doesn't it?

I was comparing this approach to how JDBC registers drivers:

java.sql.DriverManager.registerDriver(java.sql.Driver driver);

But this would be called from a static intialization block in the driver implementaion, e.g.

And getConnection() will ask the registered drivers if they can handle the url provided.

As we see with JDBC the Driver(the service provider) has to register itself, whereas, with SLF4J ILoggerFactory (the service provider), the registration (actually binding) is done automatically. This makes sense because with JDBC, we might want to use multiple databases at the same time.