Javascript RPN Calculator

RPN (Reverse Polish Notation) is a mathematical notation wherein every operator follows all of its operands, which was designed to reduce computer memory access and utilize the stack to evaluate expressions.

The syntax looks like:

rpn("3 3 +"); // => 3 + 3 => 6
rpn("2 2 + 3 *"); // => (2 + 2) * 3 => 12
rpn("2 2 3 + *"); // => (2 + 3) * 2 => 10 
rpn("2 2 3 3 / * /"); // => ((3 / 3) * 2) / 2 => 1;

A typical interview question would be to implement a RPN calculator since it is simple enough to resolve in less than an hour and it tests our ability to notice a problem that cries out for a stack based solution.
It also tests our absence from the “Introduction to Algorithms” course in college.

Obviously there are other algorithms to implement RPN, such as recursion, but using a stack will be more efficient: a stack will take O(n) times rather than O(n2) for recursion.

Of course, this has very little to do with UI programing, but we are dealing with interview questions.
Continue reading

PubSub / Observer Pattern and Coupling

PubSub (or the observer pattern) is obviously the hottest pattern in client side development, and I would like to take a shot at trying to refine the best practices for using it in a flexible and robust way.

The definition provided in the original Gang of Four book on Design Patterns states:

“Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically”

As in any design pattern, an important part is to keep the application loosely coupled and with high cohesion.
Continue reading

The Zen of Javascript

I ran across PEP 20 — The Zen of Python by Tim Peters, and figured very little needs to be changed to make it a valid javascript zen:

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch Doug.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those! let’s fake those!

Why Good Programmers Are Lazy and Dumb

I ran into an old post by Philipp Lenssen on how good programmers are lazy and dumb.
I totally agree with the title and most of the content. However, I believe that the lazy and dumb engineers are the better ones for a different reason:

Lazy:
Because code is liability, and by writing a lot of code, you are taking upon yourself (or your team) liability to test, maintain, document and improve it.
A lazy developer will first look for an existing solution that already has all the above and which is qualified to solve the aimed problem.

Dumb:
Because a dumb developer writes code that is simple enough, for dumb engineers, just as he is, to be able to understand and work with.
“Smart” engineers tend to write sophisticated programs that nobody but them or the like of them can understand. I guess it makes them feel smart.
Dumb engineers look for simple, encapsulated, loosely coupled solutions that anybody can understand.

Reinventing the Wheel

I ran into this old post by Jeff Atwood, that makes a good point. Reinventing the wheel is most probably the best way to learn about “wheels”, and about the problems they designed to solve.
There is no better way to learn about anything than actually implementing it.

However, consider a project that, say, 3 engineers are working on, and each one of them reinvents a different “wheel”?
Here’s what will happen:

  • Engineer #1 will write a HTTP server
  • Engineer #2 will write a RoR like backend MVC framework
  • Engineer #3 will write a jQuery like dom abstraction JS library

You see where this is getting…
There are at least two main problems here:

  1. This project will probably be buggy, will take forever to develop, and will be impossible to maintain.
  2. The next engineer coming after you, is more likely to have experience with jQuery than in your home brewed fooQuery.js and will probably have more desire to gain expertise with jQuery over your amazing home brewed library.

Basically the more code we own, the more liability we have to maintain, test, debug, fix, improve, write documentation etc.
Given the limited resources we all have, the last thing we need is to own more code.

This is especially true when all the above problems are already solved with efficient, fully tested, fully documented open source projects we can use. for free. with communities and all the other good stuff that comes with open source projects.

This is exactly the reason why engineers should own or participate in pet projects.
A pet project is the perfect place where its not only okay to reinvent the wheel – it is desired — this is exactly the room to do crazy things, experiment, learn, and develop your professional skills.

Software Engineering Interview Questions

Edit, 6/26/2012:
This post is my personal rant about interview questions. If you got here looking for actual programming interview questions, I can recommend these books: Cracking the Coding Interview and Programming Interviews Exposed. These books helped many engineers getting their dream jobs.

It’s no secret I’ve been in a lot of interviews in the past couple of years, both as an interviewer and as a candidate. When it comes to tech interview questions, to simplify things, I can break it into 3 major types:

  1. Implementation questions
  2. Architecture/design questions
  3. “Problem solving” questions

The first type intends to check your experience with current industry standard tools. For instance, as a javascript engineer you will be asked about specific jQuery method, what problem it designed to solve, and how you can effectively use it, how a web browser works, or what is the HTTP protocol.

The second type intends to check your software design skills, and your ability to design a complex application. As a front end engineer, you will probably asked about MVC concepts, RESTful architecture, or design patterns.

The third type intends to check how well you handle with random problems you didn’t expect. However, in many cases, this part is a tricky, and mostly out of scope.
It’s not that I don’t think a good engineer should have strong “problem solving” skills. I do.
I just think most of these “problems” you are being asked about has nothing to do with what most of us actually do on a daily basis.

In my past interviews I was asked algorithmic questions, mathematical/geometry questions and physics questions. Hell, I’m surprised I wasn’t asked to solve rocket science problems. After all, my “problem solving skills” are being measured.
Continue reading

Backbone.js Poller

Lets say you have a Backbone.js based messaging system on your application, and you want to stay synced with the server so you could alert your users when a new message arrives. You would like to call the server once every couple of seconds and ask for status updates.
Or maybe your model represents an on going background task, you want to poll for status updates.
You could start with something basic such as:

function poll(collection, delay) {
  setInterval(function(){
    collection.fetch({data: {foo: 'bar'}});
  }, delay);
}

This works, but has some flaws:

  1. You may end up running simultaneous requests hitting the browser’s allowed connection per host limit (typically 6, 2 on IE7, according to browserscope)
  2. Nothing prevents you from running the function multiple time with the same collection
  3. You can’t easily stop the process, and abort running requests
  4. It doesn’t handle cases where we want to stop polling a model on a condition (say, when it’s task is done)

This may results in unnecessary load on the server side

You could run the next request only upon successful fetch request, and write something like this:

function poll(collection, delay) {
  collection.fetch({
    data: {foo: 'bar'},
    success: function(){
      setTimeout(function(){
        poll(collection, delay);
      }, delay)
    }
  });
}

This solves #1 bit doesn’t help other issues.
It takes a little more than that, and starts smelling like a special helper is needed.
You could add a poll() and unpoll() methods to your base models or collections using inheritance or mixin.
I wouldn’t like to promote such approach since it breaks the model’s interface and introduces tight coupling between the model and application state.
This easily becomes a slippery way down to maintenance hell.
A better pattern would be to use an external helper that will keep our interfaces clean and our models stateless and decoupled.

I ended up writing a Backbone Poller, A polling helper utility for Backbone.js.
a basic usage for our messaging system will could like

var inbox = new InboxCollection();
var poller = Backbone.Poller.get(inbox, {
    delay: 2000, 
    data: {sort: 'date desc'}
});
poller.on('success', function(){
    // do something on every successful fetch
});
poller.start();

A more advanced usage for our long going offline task could look like

var options = {
    delay: 2000,
    // when this becomes false the poller will stop
    condition: function(model){
        return model.get('done') !== true; 
    }
};

var task = new OfflineTaskModel();
var poller = Backbone.Poller.get(task, options);
poller.on('complete', function(){
    // task is done, do something
});
task.set('command', 'some-long-procedure');
task.save({},{
    success: function(){
        poller.start();
        
    }
});

The code and examples are available under the MIT license in github.