简体   繁体   English

使用Scala Option验证命令行参数

[英]Using Scala Option to validate command line argument

I am using Apache commons CLI for command line parsing in a Scala utility application. 我在Scala实用程序应用程序中使用Apache commons CLI进行命令行解析。 One of the arguments is a database port number ( --port= ) that overrides the default "5432" (for PostgreSQL). 其中一个参数是数据库端口号( --port= ),它覆盖了默认的“5432”(对于PostgreSQL)。 I am trying to use the Option class to assist in the validation. 我正在尝试使用Option类来协助验证。 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. 端口号必须是1到65535之间的整数,包括1和65535。

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)

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: 我承认我不是百分百肯定,如果出现问题你想要抛出什么,或者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

I guess it's a good time for me to explore Validation. 我想这是我探索验证的好时机。

import scalaz._
import Scalaz._

val port = {
  def checkRange(port: Int): Validation[String, Int] = {
    if (port < 1 || port > 65535) "port not in [1-65535]".fail
    else port.success
  }
  commandLine.getOptionValue("port", "5432")
    .parseInt.flatMap(checkRange) match {
    case Failure(e) => throw new IllegalArgumentException(e.toString)
    case Success(port) => port
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM