使用Scala Option验证命令行参数

Ral*_*lph 3 validation scala

我在Scala实用程序应用程序中使用Apache commons CLI进行命令行解析.其中一个参数是数据库端口号(--port=),它覆盖了默认的"5432"(对于PostgreSQL).我正在尝试使用Option类来协助验证.这是我想出的代码.有更好的方法来进行验证吗?

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
Run Code Online (Sandbox Code Playgroud)

端口号必须是1到65535之间的整数,包括1和65535.

这样做会更好吗?为什么或者为什么不?

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)
Run Code Online (Sandbox Code Playgroud)

agi*_*eel 5

我承认我不是百分百肯定,如果出现问题你想要抛出什么,或者5432是每个错误值的默认端口,但这是我要做的:

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
Run Code Online (Sandbox Code Playgroud)

  • 然后你可以使用默认值定义给定的方法:`def getPort(candidate:Option [String] = Some("5432"))= ...` (2认同)