Tag Archives: parameters

function argument sequence

In many APIs one is confronted with the question, which parameter stands for what.

Consider a call in a code you’re reading or trying to write:

is_funkier(1,2)

Is 2 funkier than 1 or vice versa? A long time ago I asked a childhood friends’ father if I could try program their game console. The response was that one has to know a programming language, such as basic. On a request to quote a bit from a programming language I heard “begin, end, goto”. ‘Sounds like English to me’, I replied,’I could do that’. And now, years later I want to program close to English: not Shakespeare but rather a DSL.

A minimal example of how I would improve the API above [1. in Lua here, but not limited to Lua in principle]. Test:

assert( not is(1).funkier_than(1) )
assert( is(2).funkier_than(1) )

And an easy way of implementing the API [2. returning a function would suffice in case of one query]:

local function is(subject)
   local queries = {}

   queries.funkier_than = function(what)
      return subject > what
   end

   -- queries extensible
   -- if subject is stored in the table
   -- queries.subject = subject
  
   return queries
end

Depending on the usage, such constrained argument ordering may improve readability and thus perhaps reduce risks associated with writing code.

To further extend the DSL, further mechanisms can be used of the language of choice. There are some languages that can help remove clutter even further by eliminating punctuation. See also: a nice introduction to creating readable DSLs in Groovy.

Update:

At the time of writing the post was intended as a quick demonstration how such queries/assertions could be implemented. The well known DSLs with this idea are, of course, rspec, Fluent Assertions, AssertJ, with various implementations available in Lua as well