#1834 Javascript-ish options objects using it-blocks

dobesv Tue 13 Mar 2012

I recently happened upon this idea of using it-blocks to pass a bunch of parameters to a method. This would look a lot like how they do options in Javascript, for example the famous jQuery ajax operation might be defined something like:

const class AjaxOpts
{
 new make(|This| init) { init(this) }
 const Str method := "GET"
 const Str url
 const Str format
 const Str:Str headers
 const |AjaxResult| success
 const |AjaxResult| failure
 // ... and so on ...

}

class Jquery
{
  Future ajax(|AjaxOpts| init)
  {
    AjaxOpts opts = AjaxOpts(init)
    // .. now use opts.whatever to decide what to do
  }
}

// Usage:

Jquery().ajax 
{
  url= ...
  format="json"
  success = { echo("Hooray!") }
  failure = { echo("Booooo!") }
}

It seems like it could be a helpful pattern for methods where I'd normally use named parameters (in Python, say) or have multiple versions of the method with the same name and different types of parameter (like in Java). It allows me to keep my terminology intact (I don't need to think of 5 ways of saying "read") without having a long parameter list encompassing all cases. In my case I am playing with making an Async I/O library and think it would be helpful for basic operations like connect, read, and write that are not unlike Jquery.ajax in that there can be a number of options and parameter types. Also for database and API wrappers the same applies.

Has anyone gone down this road before? What are the pitfalls? Is this just a symptom of brain rot from doing a bunch of node.js and jQuery programming?

brian Tue 13 Mar 2012

Convention is to use Str:Obj map:

out.writeObj(obj, ["indent":2, "skipErrors":true])

KevinKelley Tue 13 Mar 2012

The it-block ctor gives you some checking, though. The map method doesn't even tell you what the possibilities are, let alone tell you when you've missed one. Or mistyped its keystring, or given it "true" instead of true... Only way to find out is to run it and see what happens.

Login or Signup to reply.