Data vs Logic. JSON vs Calling Functions.
Yesterday, at Spain.js, a library called Scoped HTTP Client got mentioned during one of the talks. While I agree that the native HTTP client in node.js is too low level for the most common use-cases, I find that there are fare better alternatives than the mentioned library.
To me, programming is about data. The purpose of our programs are to manipulate data and preferably we also describe our programs using as data rather than logic. I love declarative programming. If you were in Madrid yesterday and saw my talk, you probably already got that. I showed how to build an HTTP API from declaring a data structure - without adding custom logic for each model that we might add.
So, this is a very basic example for the Scoped HTTP Client library:
var client = scopedClient.create('http://github.com/api/v2/json')
.header('accept', 'application/json')
.path('user/show/technoweenie')
.get()(function(err, resp, body) {
/* do stuff here... */
});
This is the same thing using the library Request instead. I’m actually not sure about the url, but that just proves that the previous example is slightly unclear:
request({
url: 'http://github.com/api/v2/json/user/show/technoweenie',
headers: { accept: 'application/json' },
type: 'GET' /* This is the default, so it can be omitted */
}, function(err, resp, body) {
/* do stuff here... */
});
Now, which one do you prefer?
In the first case we call four functions. Each function modifies the state of some internal object, but it doesn’t really DO anything until the last function call. In case we want to specify more things, there will probably be even more function calls.
In the second case we specify everything about our request in a single object. This makes it very easy to modify that object before we finally pass it in. If it was to be created dynamically with would just have to do operations on a transparent piece of json-data, which is what we’re doing most of the time when we’re coding JavaScript. If we were to do the same thing in the first example we would have to work on an abstraction that has been created on top of the actual data. We would have to call functions for every change we would like to do, rather than just change values in an object.
By the way, both have support for streaming data and capabilities to POST, PUT, DELETE etc. They can be used for much more specific things than these simple examples. They are probably pretty much interchangeable. But the interfaces for them, the way you call them, is very different.
While it’s interesting to talk about how to do HTTP-requests, the real issue here is of course how to write nice interfaces for other programmers to use. I find that both of these patterns are very common, but I can’t really understand why. I know which one I like.
Data > Logic
Some transparency > Too much abstraction