哪种功能技术无需通过功能传递配置

时间:2019-04-24 15:14:55

标签: scala playframework functional-programming

随着我对FP的深入研究,我对存储从配置文件加载的设置的“最佳”方式感到好奇。我刚刚创建了一个带有所有必要配置变量的case类,并在应用程序启动时进行了设置。然后,我将该案例类传递给需要其信息的任何函数。

但是,这似乎很烦人,特别是当设置案例类必须通过许多函数传播时。有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

Reader monad提供了一种传播配置的方式,而不必在需要它的所有函数中将其作为参数传递。对比以下两个实现:

可通过Reader[Config, String]从上下文中获取配置

object ConfigFunctional extends App {
  case class Config(username: String, password: String, host: String)

  def encodeCredentials: Reader[Config, String] = Reader { config =>
    Base64.getEncoder.encodeToString(s"${config.username}:${config.password}".getBytes())
  }

  def basicAuth(credentials: String): Reader[Config, String] = Reader { config =>
    Http(s"${config.host}/HTTP/Basic/")
      .header("Authorization", s"Basic $credentials")
      .asString
      .body
  }

  def validateResponse(body: String): Reader[Config, Either[String, String]] = Reader { _ =>
    if (body.contains("Your browser made it"))
      Right("Credentials are valid!")
    else
      Left("Wrong credentials")
  }

  def program: Reader[Config, Either[String, String]] = for {
    credentials       <- encodeCredentials
    response          <- basicAuth(credentials)
    validation        <- validateResponse(response)
  } yield validation


  val config = Config("guest", "guest", "https://jigsaw.w3.org")
  println(program.run(config))
}

配置作为参数传入

object ConfigImperative extends App {
  case class Config(username: String, password: String, host: String)

  def encodeCredentials(config: Config): String = {
    Base64.getEncoder.encodeToString(s"${config.username}:${config.password}".getBytes())
  }

  def basicAuth(credentials: String, config: Config): String = {
    Http(s"${config.host}/HTTP/Basic/")
      .header("Authorization", s"Basic $credentials")
      .asString
      .body
  }

  def validateResponse(body: String): Either[String, String] = {
    if (body.contains("Your browser made it"))
      Right("Credentials are valid!")
    else
      Left("Wrong credentials")
  }

  def program(config: Config): Either[String, String] = {
    val credentials = encodeCredentials(config)
    val response    = basicAuth(credentials, config)
    val validation  = validateResponse(response)
    validation
  }

  val config = Config("guest", "guest", "https://jigsaw.w3.org")
  println(program(config))
}

两个实现都应该输出Right(Credentials are valid!),但是请注意,在第一个实现config: Config中如何不是方法参数,例如,对比度encodeCredentials

def encodeCredentials: Reader[Config, String]
def encodeCredentials(config: Config): String

Config出现在返回类型中,而不是参数。我们可以将其解释为含义

  

“当encodeCredentials在提供以下内容的上下文中运行时   Config,那么它将产生String的结果。”

此处的“上下文”由Reader单子表示。

此外,请注意,即使在主要业务逻辑中,Config也不是一个参数

def program: Reader[Config, Either[String, String]] = for {
  credentials       <- encodeCredentials
  response          <- basicAuth(credentials)
  validation        <- validateResponse(response)
} yield validation

我们通过Config函数让方法在包含run的上下文中求值:

program.run(config)

要运行上述示例,我们需要以下依赖项

    scalacOptions += "-Ypartial-unification",
    libraryDependencies ++= Seq(
      "org.typelevel" %% "cats-core" % "1.6.0", 
      "org.scalaj" %% "scalaj-http" % "2.4.1"
    )

和进口

import cats.data.Reader
import java.util.Base64
import scalaj.http.Http