Saturday, May 09, 2015

Scala Params library

This post will present a small scala library that I've written for keeping track of parameters in software. The library is called Params, and consists of one object and one trait, both called Params. With Params, you can create code like this:


import se.jt.Params

class AppParams extends Params {

  import Params._
  val name =     "hi"     ## "this is a string param"
  val flag =     false     ## "set this flag to allow separate mode of operation"
  val num =     100     ## "this number could be important"
  val inPath = ReqString("without a path to handle we can't continue!")
}


val p = new AppParams
val opts = p.opts
opts("name").update("bruce")
opts("flag").update("true")
opts("num").update("42")
opts("inPath").update("my-file.txt")

Params uses reflection to update any fields in the Params object using the string-name of that field, as long as it has one of the special types in the Params object: Plong, Ping, Pouble, Pring Poolean or Plist.

So why is this any good? First of all, having a Params object to gather all algorithm parameters is very useful, especially if you send it around as an implicit parameter to your functions and classes so it's always available when needed. In the AppParams source the programmer can get a quick summary of the used parameters, and descriptions of these.

The real gains are not seen until we start exposing the parameters to the user, with the library CLIApp, that I describe in my next post.

No comments:

Post a Comment