Tag archives for architecture

Keep it Simple, Stupid!

Keep it Simple, Stupid!A while back I wrote a blog post on coupling and the observer pattern. Looking back, I did a pretty poor job describing what it wrong about it. I will attempt to correct this.

We all want simple and descriptive code. Code that is self documented. Code that makes sense, Code that tells us a story. Lets look at a kind of code I have seen many times, in many different variations, using observer based asynchronous javascript code:

 
var ListView = {
  init: function() {
    this.feed.onItemsReady(this.onFeedItemsReady);
  },
  onFeedItemsReady: function(items){
    // do something
  }
  // ...
}

At first, this looks descriptive, and it is, kinda. It’s an object describing the implementation of a publisher it is observing.
That doesn’t sound right. It is telling us about the implementation details and why it is doing things rather than what this object is responsible for and what it is doing. We already know all that!
Continue reading »

Posted in Javascript | Leave a comment

3 Tips For Writing Better Backbone Views

Backbone
One of the good things about Backbone.js is it doesn’t tell us how to do things. It leaves it for us to decide what are the best practices for writing views (or any components).
This is also one of the worst things about Backbone. it makes it almost too easy to take the wrong path, and write views that will be hard to maintain.
The principle we should follow when writing a view is to keep it encapsulated, and keep it as “dumb” as possible – a view should know only the bare minimum it needs to know in order to do it’s job, and do bare minimum it has to do.

Here are 3 simple tips that can help us achieve this:
Continue reading »

Posted in Backbone, Javascript | 5 Comments

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 »

Posted in Javascript | 1 Comment

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.

Posted in Javascript | Leave a comment

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 »

Posted in Javascript | 5 Comments

Book Review: RESTful Web Services

 I’m working on a project that includes writing a client for a fairly sophisticated RESTful API.

To get some better understanding of both client and server RESTful philosophy I purchased and read RESTful Web Services by Leonard Richardson, Sam Ruby (O’Reilly Media, 2008).

I tend to agree with the foreword by David Heinemeier Hansson: “Every developer working with the Web needs to read this book.”

The web is RESTful and therefor, when working with the web one shall at least understand RESTful concepts.

This book is doing a great job describing to details the concepts of addressability, statelessness, connectedness, and the uniform interface, and clarifying why they are important fundamentals of the web.
It gives a great overview of HTTP, URIs, Design of a REST server and client.

If I had to take one thing from the book, I would take the importance of state management.
It is crucial to understand where the state of the application belongs to.
Saving the application state on the back-end breaks the stateless nature of a web app, and could end up with an application that is hard to maintain and scale.
Keeping the state in the client side (or even better – in the URI), and keeping a sane, loosely coupled design leads to scalable web application.

One thing I was not very impressed with are the code examples.
I skipped most of them, since I didn’t buy this book to learn how to implement a REST server using RoR or Django, but choosing XHTML as the document format is very odd, and using a <div> or a <span> to represent semantic data is even odder.
Calling HTML5 XHTML5 is annoying, but given this was published in 2008 I given it the benefit of the doubt.

Bottom line, this was a good read and I highly recommend it.
If you are looking for a book to give you some detail oriented overview of REST concepts, this book is for you.

Posted in Books | Leave a comment

Javascript Design Patterns: Strategy

For a quick assignment I was asked to write the following program:

In the language of your choosing build an application that, given an English language document as input, builds a data structure capturing the count of each word in the document.

Bonus:
Create an inverted index as well: a mapping of the words to absolute positions in the document.

As context, this is a foundational algorithm for search systems and information retrieval. Be sure to consider accuracy, complexity, and intent in the design of your program.

The last phrase was the one that got me thinking.
This sounded a little vague, so I started thinking what kind of design I can implement that would be flexible enough so I can apply the algorithms later.
This kind of program usually runs on the back end using Java/Python/etc, but obviously, the language of my choice was javascript.

I started by defining a master processor:

var Processor = function(doc) {
    this.doc = doc;
};
Processor.prototype.parse = function(parser, sorter) {
    data = parser.parse(this.doc);
    if (sorter && typeof sorter.sort === 'function') {
        return sorter.sort(data);
    }
    else {
        return data;
    }
};

This processor gets a document (in our simple example, a long string) and has parse method, which accepts a “parser” object that has a parse() method and an optional “sorter” object that has a sort() method.
As the names suggest, the former will parse the document, and the latter will sort the results.
This use of the Strategy Design Pattern will allow the application to be flexible for algorithm changes, in the future.

First, I defined an abstract Parser object.
This object is responsible to convert the input to a standard format, and apply an algorithm

var Parser = function(){};
/**
 * The implementation will return an object literal 
 * with the format {word: num, word: num ...}
 * 
 * @param str {String}
 * @returns {Object}
 */
Parser.prototype.parse = function(str){
    throw 'please extned abstract object';
};

/**
 * Convert an object literal into a sortable array
 * with the format [[word, num], [word, num], ...]
 * 
 * @param data {Object}
 * @returns {Array}
 */
Parser.prototype.convert = function(data) {
    var arr = [],
        data = data || {};
    for(var key in data) {
        if(data.hasOwnProperty(key)) {
            arr.push([key, data[key]]);
        }
    }
    return arr;
};

My next step was defining the parsers I was requested to write:
One for capturing the count of each word in the document:

var CountParser = function(arr) {
    this.arr = arr;
};
CountParser.prototype = new Parser; // extend the base parser
CountParser.prototype.parse = function(str) {
    var value, i, l, data = {},
        arr = str.split(/[\s]+/);
    for(i=0, l=arr.length; i<l; i++) {
        value = arr[i];
        data[value] = data[value] || 0;
        data[value]++;
    }
    // convert our object literal into a sortable array
    return this.convert(data); 
};

And another one for a mapping of the words to absolute positions in the document:

var IndexParser = function(arr) {
    this.arr = arr;
};
IndexParser.prototype = new Parser; 
IndexParser.prototype.parse = function(str) {
    var value, i, l, data = {},
        arr = str.split(/[\s]+/);
    for(i=0, l=arr.length; i<l; i++) {
        value = arr[i];
        if( ! data[value] ) {
            data[value] = i;
        }
    }
    return this.convert(data);
};

Next, I defined my Sorter object. It is an object that takes a comparator function as an argument and can later be ran agains arrays using the Array.sort method:

var Sotrer = function(comparator) {
    this.comparator = comparator;
};
Sotrer.prototype.sort = function(arr) {
    arr.sort(this.comparator);
    return arr;
};

Then, I implemented the two basic comparator algorithms: Ascending and Descending:

var ascCompare = function(a, b){
    return a[1] - b[1];
};
var descCompare = function(a, b){
    return b[1] - a[1];
};

The only thing left now is to run an example:

var doc = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?";
var processor = new Processor(doc);

var indexParser = new IndexParser(), 
    ascSorter = new Sotrer(ascCompare),
    countParser = new CountParser(),
    descSorter = new Sotrer(descCompare);
    
console.log(processor.parse(indexParser, ascSorter));
console.log(processor.parse(countParser, descSorter));

This design, based on strategy pattern, can later on take any parsing algorithm and any sorting algorithm with out the need for refactoring the core application.

Posted in Javascript | 5 Comments

Swedish Greys - a WordPress theme from Nordic Themepark.