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)
String => Option[Int].parsent: String => Validation[NumberFormatException, Int]. CallingtoOptionon the validation will give youOption[Int].