Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Scala Option to validate command line argument

I am using Apache commons CLI for command line parsing in a Scala utility application. One of the arguments is a database port number (--port=) that overrides the default "5432" (for PostgreSQL). I am trying to use the Option class to assist in the validation. Here is the code I came up with. Is there a better way to do the validation?

val port = Option(commandLine.getOptionValue("port", "5432")) map {
  try {
    val value = Integer.parseInt(_)
    if (value < 1 || value > 65535) throw new NumberFormatException
    value
  } catch {
    case ex: NumberFormatException =>
      throw new
        IllegalArgumentException("the port argument must be a number between 1 and 65535")
  }
} get

The port number must be an integer between 1 and 65535, inclusive.

Would it be better to do this? Why or why not?

val port = Option(commandLine.getOptionValue("port")) map {
  try {
    val value = Integer.parseInt(_)
    if (value < 1 || value > 65535) throw new NumberFormatException
    value
  } catch {
    case ex: NumberFormatException =>
      throw new
        IllegalArgumentException("the port argument must be a number between 1 and 65535")
  }
} getOrElse(5432)
like image 739
Ralph Avatar asked Oct 20 '25 10:10

Ralph


1 Answers

I admit I'm not 100% sure, what you want to be thrown in case something goes wrong, or if the 5432 is a default port for every wrong value, but here is what I would do:

def getPort(candidate: Option[String]) = candidate
   .map { _.toInt } // throws NumberFormatException
   .filter { v => v > 0 && v <= 65535 } // returns Option[Int]
   .getOrElse { throw new IllegalArgumentException("error message") } // return an Int or throws an exception
like image 52
agilesteel Avatar answered Oct 23 '25 00:10

agilesteel