About Achieving Polymorphism in JavaScript
About Achieving Polymorphism in JavaScript
Join the DZone community and get the full member experience.
Join For FreeJumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.
Over the weekend, I started working on a Node.js client library for Toshl’s new API. An old side project stopped working recently and I need to fix it, because life without frequent emails about my money is disorienting as hell.
The Toshl beta API opened up in July is well thought out, has good documentation and provides everything you could possibly want. I love the well granulated permissions system.
But for users of my Node.js library, I wanted to make life even simpler. Let’s look at fetching expenses.
After you authenticate – testing OAuth clients sucks, and Toshl invalidates your token very often. Think I had to refresh it four times in a five hour coding spree. – you can talk to https://api.toshl.com/expenses
to get a list of expenses for the current user.
This will return the last 30 entries.
But there are a bunch of options. You have pagination, you can set specific to
and from
dates, you can filter things by tags and by not-tags.
How can a library make this easy to use?
One approach is to offer a way of specifying an options hash when calling a function, but can we make it even simpler?
The answer lies in polymorphism.
Let’s say you have a function called toshl.expenses
, in Haskell you could do something like this:
expenses::Result expenses = general_expenses "" expenses::Number -> Result expenses N = general_expenses "?per_page="+str(N) expenses::[String] -> Result expenses tags = general_expenses "?tags="+(tags.join "&") expenses::Date -> Date -> Result expenses from to = general_expenses "?from="+str(from)+"&"+str(to) expenses::Json -> Result expenses params = general_expenses "?"+to_query(params) general_expenses::String -> Result general_expenses query = make_request "/expenses" query make_request::String -> String -> Result make_request endpoint query = ;; do stuff to read from full URL
The syntax is likely wrong, but you get what I’m pointing at. You can always call expenses
with the argument you care about and it will construct a call to the more generalized version of the function magically.
You can tell what calling expenses
will do in each case at a glance and checking what type of arguments the function accepts is trivial. Even somebody who isn’t familiar with Haskell could understand that code.
Here’s that same polymorphic code in Javascript. This time it's tested, working code.
exports.Toshl.prototype.expenses = function (params, to, callback) { var options = {}, query = ''; callback = arguments[arguments.length-1]; if (params) { if (typeof params == 'number') { options['per_page'] = params; }else if (arguments.length == 3) { options['from'] = util.iso_date(params); options['to'] = util.iso_date(to); }else if (params instanceof Array) { var tags = util.transform_tags(params); options[tags.type] = tags.tags; }else if (params instanceof Object) { options = params; ['from', 'to'].forEach(function (key) { if (options[key]) { options[key] = util.iso_date(options[key]); } }); } query = "?"+querystring.stringify(options); } this._request('/expenses'+query, callback); };
Oh, wow, what?
Even if you’re very comfortable with Javascript, you’re going to have a hard time figuring out what’s going on. It seems the majority of the function deals with translating arguments
into a query
, then it defers to this._request
for the hard work.
This is the cleanest implementation I could think of so far. Let’s investigate.
First we ensured that callback
is always the last supplied argument, that makes sense when you expect variable amounts of arguments. Everything from one to three is okay.
Then, if params
is a number, we use it to construct a ?per_page=N
query. If there are three arguments, we use the first two to construct a ?from=Date&to=Date
query. If the first argument is an Array, we use it to get tags, and if it’s an Object, we assume it represents a parameters hash for the API.
The result is that we can do this:
var toshl = new Toshl(); toshl.expenses(console.log); // prints last 30 expenses toshl.expenses(5, console.log); // prints last 5 expenses toshl.expenses("2013-10-01", new Date(), console.log); // prints all expenses between October 1st and now toshl.expenses(["coffee", "food"], console.log); // prints last 30 expenses tagged with coffee or food toshl.expenses({per_page: 10, tags: ["coffee", "food"]}, console.log) // prints last 10 expenses tagged coffee or food
The date magic is done with the wonderful moment.js library – you can supply a Date object, a date string or a moment object, but we could obviously improve on this by assuming the to
date is “now”, if none is provided.
But the code is getting complicated as it is.
Does anyone know a better way to achieve polymorphism in Javascript? I really like it when I’m using libraries, but I hate implementing it this way …
You should follow me on twitter, here.
Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.
Published at DZone with permission of Swizec Teller , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}