On 23.03.2011 02:35, Scott Sauyet wrote:
npup wrote:
 That said, I am one of those who prefer throwing immediately instead
 of if-else-ing too much and thereby having the real work being done in
 some unnecessarily indented part of the code :)

I tend to be the same way, at least in JS.  But I wouldn't like this
sort of API to dictate my program structure.

If the most common reaction to non-conformance is to throw an Error, and you want to avoid unnecessary if/else branching, you could introduce a convenience method to do both. Maybe something like

  // code code code...
  Conform.assert(spec, obj);
  // now we're safe. yay. more code code code...

The assert() method would just wrap the "acts as" method:

  Conform.assert = function (spec, obj) {
    if (!Conform.actsAs(spec, obj)) {
      throw new Error(Conform.getLastError());
    }
  };

<aside>I used "Conform" as a temporary placeholder instead of Acts or Acts.As because I'm not convinced that those are very good names for a conformance checker. I mean, yeah, it's cute to write Acts.As(something), but that breaks down as soon as you want to use any other method or property of Acts.As - such as Acts.As.info. On a semantic level, I'm also wondering what the Acts object represents. It sounds vaguely biblical, but that's not really my forte ;)</aside>

More random thoughts:
.) methods which accept an 'obj' parameter could optionally also accept an array of objects. .) another convenience wrapper for actsAs() might be violates() - similar to actsAs, but opposite results. .) there could be a check() method which would return an info object for those who want to know exactly what went wrong.

There is also an alternative to currying. "Conform" (or whatever catchy name you can come up with) could be more than a simple namespace; it could be a real constructor:

  var addrCheck = new Conform(addressSpec);
  if (addrCheck.passes(obj)) {
     // we're fine
  } else {
     throw Error(addrCheck.lastError());
  }

This way, you can have "static" methods like Conform.actsAs, Conform.check, Conform.assert, etc, and also specialized Conform objects with a stored specification object.

API design is fun. There are 1001 different ways to meet the same goal, and the more complex your requirements are, the less likely it is that two people will agree on which way is best. It's even more fun when you're in a position to lay down the law :) IMHO, it's less fun when you paint yourself into a corner by using a name like "Acts.As", because then you're basically limiting yourself to answering a single question.


--
stefan

--
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to